// Módulo: Revisão Interativa de Contratos — painel do advogado

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

  if (view === 'new')
    return <NovaRevisao currentUser={currentUser} onBack={() => setView('list')} onCreated={(id) => { setSelectedId(id); setView('detail'); }} />;
  if (view === 'detail' && selectedId)
    return <PainelAdvogado id={selectedId} onBack={() => setView('list')} />;
  return <ListaRevisoes onNew={() => setView('new')} onOpen={(id) => { setSelectedId(id); setView('detail'); }} />;
};

// ─── Lista de revisões ────────────────────────────────────────────────────────

const ListaRevisoes = ({ onNew, onOpen }) => {
  const [reviews, setReviews] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    fetch('/api/contratos/revisao', { credentials: 'include' })
      .then(r => r.json())
      .then(d => setReviews(d.data?.reviews || []))
      .finally(() => setLoading(false));
  }, []);

  return (
    <div style={{ padding: '1.5rem', maxWidth: 900, margin: '0 auto' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '1.5rem' }}>
        <div>
          <h1 style={{ fontSize: '1.375rem', fontWeight: 700, color: 'var(--pac-navy)' }}>Revisão de Contratos</h1>
          <p style={{ fontSize: '.875rem', color: '#6b7280', marginTop: '.25rem' }}>Gerencie minutas enviadas para revisão pelo cliente.</p>
        </div>
        <button className="pac-btn pac-btn-primary" onClick={onNew}>+ Nova revisão</button>
      </div>

      {loading && <div className="pac-loading">Carregando...</div>}
      {!loading && reviews.length === 0 && (
        <div style={{ textAlign: 'center', padding: '4rem 0', color: '#9ca3af' }}>
          <p style={{ fontSize: '1.125rem', marginBottom: '.5rem' }}>Nenhuma revisão criada ainda.</p>
          <p style={{ fontSize: '.875rem' }}>Clique em "+ Nova revisão" para começar.</p>
        </div>
      )}
      {!loading && reviews.length > 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: '.75rem' }}>
          {reviews.map(r => (
            <div key={r.id} className="pac-card" style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '1rem' }} onClick={() => onOpen(r.id)}>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 600, color: '#111', marginBottom: '.25rem' }}>{r.project_name}</div>
                <div style={{ fontSize: '.8125rem', color: '#6b7280' }}>
                  {r.client?.name || 'Sem cliente vinculado'}
                  {r.case ? ` · Caso ${r.case.number}` : ''}
                </div>
              </div>
              <div style={{ fontSize: '.75rem', color: '#9ca3af', flexShrink: 0 }}>
                {new Date(r.created_at).toLocaleDateString('pt-BR')}
              </div>
              <span style={{ color: '#9ca3af', fontSize: '1.25rem' }}>›</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

// ─── Formulário de nova revisão ──────────────────────────────────────────────

const NovaRevisao = ({ currentUser, onBack, onCreated }) => {
  const [clients, setClients] = React.useState([]);
  const [cases, setCases] = React.useState([]);
  const [projectName, setProjectName] = React.useState('');
  const [clientId, setClientId] = React.useState('');
  const [caseId, setCaseId] = React.useState('');
  const [docxFile, setDocxFile] = React.useState(null);
  const [mdFile, setMdFile] = React.useState(null);
  const [recipients, setRecipients] = React.useState([{ recipient_name: '', login: '', recipient_email: '', password: '' }]);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState('');
  const [credentials, setCredentials] = React.useState(null); // result after creation
  const [createdId, setCreatedId] = React.useState(null);
  const [createdLink, setCreatedLink] = React.useState('');
  const [mdWarnings, setMdWarnings] = 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 addRecipient = () => setRecipients(prev => [...prev, { recipient_name: '', login: '', recipient_email: '', password: '' }]);
  const removeRecipient = (i) => setRecipients(prev => prev.filter((_, idx) => idx !== i));
  const updateRecipient = (i, field, val) => setRecipients(prev => prev.map((r, idx) => idx === i ? { ...r, [field]: val } : r));

  const slugify = (s) => s.toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 30);

  const suggestLogin = (i) => {
    const r = recipients[i];
    if (!r.recipient_name) return;
    const sug = `${slugify(projectName || 'projeto')}-${slugify(r.recipient_name)}`;
    updateRecipient(i, 'login', sug);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    if (!projectName.trim()) { setError('Nome do projeto obrigatório.'); return; }
    if (!docxFile) { setError('Arquivo .docx obrigatório.'); return; }
    if (!mdFile) { setError('Arquivo .md obrigatório.'); return; }
    const validRec = recipients.filter(r => r.recipient_name.trim());
    if (validRec.length === 0) { setError('Pelo menos um destinatário é obrigatório.'); return; }

    const fd = new FormData();
    fd.append('project_name', projectName.trim());
    if (clientId) fd.append('client_id', clientId);
    if (caseId) fd.append('case_id', caseId);
    fd.append('docx', docxFile);
    fd.append('md', mdFile);
    fd.append('recipients', JSON.stringify(validRec.map(r => ({
      recipient_name: r.recipient_name.trim(),
      login: r.login.trim() || undefined,
      recipient_email: r.recipient_email.trim() || undefined,
      password: r.password?.trim() || undefined,
    }))));

    setSending(true);
    try {
      const res = await fetch('/api/contratos/revisao', {
        method: 'POST',
        credentials: 'include',
        body: fd,
      });
      const json = await res.json();
      if (!res.ok) { setError(json.error || 'Erro ao criar revisão.'); return; }
      setCreatedId(json.data.review_id);
      setCreatedLink(json.data.link);
      setCredentials(json.data.credentials);
      setMdWarnings(json.data.warnings || []);
    } catch (err) {
      setError('Erro de conexão.');
    } finally {
      setSending(false);
    }
  };

  // ── Tela de credenciais (pós-criação) ──
  if (credentials) {
    return (
      <div style={{ padding: '1.5rem', maxWidth: 700, margin: '0 auto' }}>
        <div style={{ background: '#f0fdf4', border: '1.5px solid #22c55e', borderRadius: 12, padding: '1.5rem', marginBottom: '1.5rem' }}>
          <h2 style={{ color: '#15803d', fontWeight: 700, marginBottom: '.75rem' }}>✓ Revisão criada com sucesso!</h2>
          {mdWarnings.length > 0 && (
            <div style={{ background: '#fef9c3', borderRadius: 8, padding: '.75rem 1rem', marginBottom: '1rem', fontSize: '.875rem', color: '#854d0e' }}>
              <strong>Avisos do parser:</strong> {mdWarnings.join(' | ')}
            </div>
          )}
          <div style={{ marginBottom: '1rem' }}>
            <div style={{ fontSize: '.8125rem', fontWeight: 600, color: '#374151', marginBottom: '.375rem' }}>Link de revisão (único por contrato):</div>
            <div style={{ display: 'flex', gap: '.5rem', alignItems: 'center' }}>
              <input readOnly value={createdLink} style={{ flex: 1, padding: '.5rem .75rem', border: '1.5px solid #d1d5db', borderRadius: 8, fontSize: '.875rem', background: '#f9fafb' }} />
              <button className="pac-btn pac-btn-secondary" onClick={() => navigator.clipboard.writeText(createdLink)}>Copiar link</button>
            </div>
          </div>
          <div style={{ fontSize: '.875rem', fontWeight: 600, color: '#374151', marginBottom: '.75rem' }}>Credenciais por destinatário (mostradas apenas uma vez):</div>
          {credentials.map((cred, i) => (
            <div key={i} style={{ background: '#fff', border: '1.5px solid #d1d5db', borderRadius: 10, padding: '1rem', marginBottom: '.75rem' }}>
              <div style={{ fontWeight: 700, marginBottom: '.5rem', color: '#0d0d6b' }}>{cred.recipient_name}</div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '.5rem', fontSize: '.875rem' }}>
                <div>
                  <div style={{ fontSize: '.75rem', color: '#6b7280', marginBottom: '.2rem' }}>Login</div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '.375rem' }}>
                    <code style={{ background: '#f3f4f6', padding: '.25rem .5rem', borderRadius: 6, fontFamily: 'monospace', fontSize: '.875rem' }}>{cred.login}</code>
                    <button className="pac-btn-icon" title="Copiar" onClick={() => navigator.clipboard.writeText(cred.login)}>⧉</button>
                  </div>
                </div>
                <div>
                  <div style={{ fontSize: '.75rem', color: '#6b7280', marginBottom: '.2rem' }}>Senha</div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '.375rem' }}>
                    <code style={{ background: '#fef9c3', padding: '.25rem .5rem', borderRadius: 6, fontFamily: 'monospace', fontSize: '.875rem' }}>{cred.password_plain}</code>
                    <button className="pac-btn-icon" title="Copiar" onClick={() => navigator.clipboard.writeText(cred.password_plain)}>⧉</button>
                  </div>
                </div>
              </div>
            </div>
          ))}
          <div style={{ display: 'flex', gap: '.75rem', marginTop: '1rem', flexWrap: 'wrap' }}>
            <button className="pac-btn pac-btn-primary" onClick={() => {
              const all = `Link: ${createdLink}\n\n${credentials.map(c => `${c.recipient_name}\nLogin: ${c.login}\nSenha: ${c.password_plain}`).join('\n\n')}`;
              navigator.clipboard.writeText(all);
            }}>Copiar tudo</button>
            <button className="pac-btn pac-btn-secondary" onClick={() => onCreated(createdId)}>Ver painel da revisão</button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={{ padding: '1.5rem', maxWidth: 760, margin: '0 auto' }}>
      <button className="pac-btn pac-btn-ghost" style={{ marginBottom: '1rem' }} onClick={onBack}>← Voltar</button>
      <h1 style={{ fontSize: '1.25rem', fontWeight: 700, color: 'var(--pac-navy)', marginBottom: '1.5rem' }}>Nova revisão de contrato</h1>

      <form onSubmit={handleSubmit}>
        {/* Informações gerais */}
        <div className="pac-card" style={{ marginBottom: '1rem' }}>
          <div style={{ fontWeight: 700, marginBottom: '1rem', color: '#374151' }}>Informações gerais</div>
          <div style={{ marginBottom: '.875rem' }}>
            <label className="pac-label">Nome do projeto *</label>
            <input className="pac-input" value={projectName} onChange={e => setProjectName(e.target.value)} placeholder="Ex: Acordo de Acionistas – Empresa XYZ" required />
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '.875rem' }}>
            <div>
              <label className="pac-label">Cliente (opcional)</label>
              <SearchableSelect className="pac-input" value={clientId} onChange={e => setClientId(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>
              <label className="pac-label">Caso (opcional)</label>
              <SearchableSelect className="pac-input" value={caseId} onChange={e => setCaseId(e.target.value)} disabled={!clientId}>
                <option value="">— Sem caso vinculado —</option>
                {cases.map(c => <option key={c.id} value={c.id}>{c.number} – {c.title}</option>)}
              </SearchableSelect>
            </div>
          </div>
        </div>

        {/* Arquivos */}
        <div className="pac-card" style={{ marginBottom: '1rem' }}>
          <div style={{ fontWeight: 700, marginBottom: '.5rem', color: '#374151' }}>Arquivos do contrato</div>
          <div style={{ fontSize: '.8125rem', color: '#6b7280', marginBottom: '1rem', lineHeight: 1.55 }}>
            Você sobe <strong>dois arquivos</strong>: a minuta original em <code>.docx</code> (o que o cliente baixa)
            e a estrutura em <code>.md</code> com cláusulas + explicações em linguagem simples (o que o cliente lê online).
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '.875rem' }}>
            <div>
              <label className="pac-label">Minuta (.docx) * <span style={{ fontWeight: 400, color: '#9ca3af' }}>— download pelo cliente</span></label>
              <input type="file" accept=".docx" className="pac-input" onChange={e => setDocxFile(e.target.files?.[0] || null)} required />
            </div>
            <div>
              <label className="pac-label">Estrutura (.md) * <span style={{ fontWeight: 400, color: '#9ca3af' }}>— leitura web com explicações</span></label>
              <input type="file" accept=".md,text/markdown,text/plain" className="pac-input" onChange={e => setMdFile(e.target.files?.[0] || null)} required />
            </div>
          </div>
          <details style={{ marginTop: '1rem', background: '#f9fafb', borderRadius: 8, padding: '.75rem 1rem', border: '1px solid #e5e7eb' }}>
            <summary style={{ cursor: 'pointer', fontSize: '.8125rem', fontWeight: 600, color: '#0d0d6b' }}>📖 Como estruturar o .md?</summary>
            <div style={{ marginTop: '.75rem', fontSize: '.8125rem', color: '#374151', lineHeight: 1.65 }}>
              <p style={{ marginBottom: '.5rem' }}>Cada cláusula começa com <code>## Cláusula N — Título</code>, seguida do texto formal e de um bloco de explicação:</p>
              <pre style={{ background: '#1f2937', color: '#e5e7eb', borderRadius: 6, padding: '.75rem', fontSize: '.75rem', overflow: 'auto', lineHeight: 1.5, margin: '.5rem 0' }}>{`## Cláusula 1 — Objeto

O presente contrato tem por objeto...
(texto formal copiado do .docx)

:::explicacao
**O que é isso?**
Define o que a empresa faz...

**Por que existe?**
Para deixar claro o escopo...
:::

## Cláusula 2 — ...`}</pre>
              <ul style={{ margin: '.5rem 0 0 1.25rem', fontSize: '.75rem', color: '#6b7280' }}>
                <li>Subitens (1.1, "(i)", "Parágrafo Único") ficam <strong>dentro</strong> da cláusula pai, não viram nova <code>##</code></li>
                <li>O bloco <code>:::explicacao ... :::</code> vem <strong>depois</strong> do texto formal</li>
                <li>Use <strong>**negrito**</strong> para destacar termos</li>
                <li>Não precisa do <code>.docx</code> casar exatamente — ele é só para download</li>
              </ul>
            </div>
          </details>
        </div>

        {/* Destinatários */}
        <div className="pac-card" style={{ marginBottom: '1rem' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '1rem' }}>
            <div style={{ fontWeight: 700, color: '#374151' }}>Destinatários</div>
            <button type="button" className="pac-btn pac-btn-secondary" onClick={addRecipient}>+ Adicionar</button>
          </div>
          {recipients.map((rec, i) => (
            <div key={i} style={{ border: '1.5px solid #e5e7eb', borderRadius: 10, padding: '1rem', marginBottom: '.75rem', background: '#f9fafb' }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr auto', gap: '.75rem', alignItems: 'end' }}>
                <div>
                  <label className="pac-label">Nome *</label>
                  <input className="pac-input" value={rec.recipient_name} onChange={e => updateRecipient(i, 'recipient_name', e.target.value)} onBlur={() => !rec.login && suggestLogin(i)} placeholder="Ex: João Silva" />
                </div>
                <div>
                  <label className="pac-label">Login <span style={{ fontWeight: 400, color: '#9ca3af' }}>(gerado auto)</span></label>
                  <input className="pac-input" value={rec.login} onChange={e => updateRecipient(i, 'login', e.target.value)} placeholder={`${slugify(projectName || 'projeto')}-...`} />
                </div>
                <div>
                  <label className="pac-label" style={{ display: 'flex', alignItems: 'center', gap: '.375rem' }}>
                    E-mail
                    <span style={{ fontSize: '.7rem', background: '#f3f4f6', color: '#9ca3af', padding: '1px 6px', borderRadius: 4 }}>Fase 2</span>
                  </label>
                  <input className="pac-input" value={rec.recipient_email} onChange={e => updateRecipient(i, 'recipient_email', e.target.value)} placeholder="opcional" disabled title="Envio por e-mail disponível em breve" style={{ cursor: 'not-allowed', opacity: .5 }} />
                </div>
                {recipients.length > 1 && (
                  <button type="button" onClick={() => removeRecipient(i)} style={{ background: 'none', border: 'none', color: '#ef4444', cursor: 'pointer', fontSize: '1.125rem', paddingBottom: '.25rem' }} title="Remover">✕</button>
                )}
              </div>
              <div style={{ marginTop: '.75rem' }}>
                <label className="pac-label">Senha <span style={{ fontWeight: 400, color: '#9ca3af' }}>(opcional — se em branco, gerada automaticamente)</span></label>
                <input className="pac-input" value={rec.password} onChange={e => updateRecipient(i, 'password', e.target.value)} placeholder="Mínimo 6 caracteres" autoComplete="new-password" />
              </div>
              <div style={{ marginTop: '.5rem', fontSize: '.75rem', color: '#9ca3af' }}>
                Método de envio:
                <span style={{ marginLeft: '.5rem', background: '#e5e7eb', borderRadius: 4, padding: '1px 8px', fontSize: '.7rem', color: '#374151', fontWeight: 600 }}>Link manual</span>
                <span style={{ marginLeft: '.375rem', background: '#f3f4f6', borderRadius: 4, padding: '1px 8px', fontSize: '.7rem', color: '#9ca3af' }} title="Disponível em breve (Fase 2)">E-mail — em breve</span>
              </div>
            </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 revisão'}</button>
        </div>
      </form>
    </div>
  );
};

// ─── Painel do advogado ───────────────────────────────────────────────────────

const PainelAdvogado = ({ id, onBack }) => {
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [expandedCell, setExpandedCell] = React.useState(null);
  const [addingRecipient, setAddingRecipient] = React.useState(false);
  const [newRecipName, setNewRecipName] = React.useState('');
  const [newRecipPwd, setNewRecipPwd] = React.useState('');
  const [regenPwdInput, setRegenPwdInput] = React.useState({}); // accessId → custom pwd typed
  const [regen, setRegen] = React.useState({}); // accessId → { password_plain }
  const [toast, setToast] = React.useState('');

  const load = () => {
    setLoading(true);
    fetch(`/api/contratos/revisao/${id}`, { credentials: 'include' })
      .then(r => r.json())
      .then(d => setData(d.data))
      .finally(() => setLoading(false));
  };
  React.useEffect(load, [id]);

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

  const exportReport = async ({ onlyCommented = false } = {}) => {
    const qs = onlyCommented ? '?only_commented=1' : '';
    const r = await fetch(`/api/contratos/revisao/${id}/relatorio${qs}`, { credentials: 'include' });
    if (!r.ok) { showToast('Erro ao gerar relatório.'); return; }
    const blob = await r.blob();
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = onlyCommented ? `relatorio-comentadas.md` : `relatorio.md`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const handleAddRecipient = async () => {
    if (!newRecipName.trim()) return;
    const pwd = newRecipPwd.trim();
    if (pwd && pwd.length < 6) { showToast('Senha deve ter ao menos 6 caracteres.'); return; }
    const r = await fetch(`/api/contratos/revisao/${id}/acessos`, {
      method: 'POST', credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ recipient_name: newRecipName.trim(), password: pwd || undefined }),
    });
    const json = await r.json();
    if (!r.ok) { showToast(json.error || 'Erro.'); return; }
    showToast(`Adicionado: ${newRecipName}. Senha: ${json.data.password_plain}`);
    setNewRecipName(''); setNewRecipPwd(''); setAddingRecipient(false); load();
  };

  const handleRegenPassword = async (accessId) => {
    const pwd = (regenPwdInput[accessId] || '').trim();
    if (pwd && pwd.length < 6) { showToast('Senha deve ter ao menos 6 caracteres.'); return; }
    const r = await fetch(`/api/contratos/revisao/${id}/acessos/${accessId}/regerar-senha`, {
      method: 'POST', credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ password: pwd || undefined }),
    });
    const json = await r.json();
    if (r.ok) {
      setRegen(prev => ({ ...prev, [accessId]: json.data.password_plain }));
      setRegenPwdInput(prev => ({ ...prev, [accessId]: '' }));
    } else showToast(json.error || 'Erro ao regerar senha.');
  };

  const getComment = (clauseId, accessId) =>
    data?.comments?.find(c => c.clause_id === clauseId && c.access?.id === accessId) || null;

  const statusBadge = (access) => {
    if (access.completed_at) return <span style={{ background: '#dcfce7', color: '#15803d', borderRadius: 20, padding: '2px 8px', fontSize: '.7rem', fontWeight: 700 }}>Concluído</span>;
    if (access.first_access_at) return <span style={{ background: '#dbeafe', color: '#1d4ed8', borderRadius: 20, padding: '2px 8px', fontSize: '.7rem', fontWeight: 700 }}>Acessou</span>;
    return <span style={{ background: '#f3f4f6', color: '#9ca3af', borderRadius: 20, padding: '2px 8px', fontSize: '.7rem', fontWeight: 700 }}>Não acessou</span>;
  };

  const commentBadge = (comment) => {
    if (!comment) return <span style={{ color: '#d1d5db', fontSize: '.75rem' }}>—</span>;
    const cfg = { duvida: ['#dbeafe','#1d4ed8','Dúvida'], alteracao: ['#fef3c7','#92400e','Sugestão'], aprovacao: ['#dcfce7','#15803d','Aprovado'] }[comment.comment_type] || ['#f3f4f6','#555','?'];
    return <span style={{ background: cfg[0], color: cfg[1], borderRadius: 20, padding: '2px 8px', fontSize: '.7rem', fontWeight: 700, cursor: 'pointer' }}>{cfg[2]}</span>;
  };

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

  const { review, clauses, accesses, comments } = data;
  const link = `${window.location.origin}/revisao/${review.public_token}`;

  return (
    <div style={{ padding: '1.25rem', maxWidth: 1100, margin: '0 auto' }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: '1rem', marginBottom: '1.5rem', flexWrap: 'wrap' }}>
        <button className="pac-btn pac-btn-ghost" onClick={onBack}>← Voltar</button>
        <div style={{ flex: 1 }}>
          <h1 style={{ fontSize: '1.25rem', fontWeight: 700, color: 'var(--pac-navy)' }}>{review.project_name}</h1>
          {review.client && <div style={{ fontSize: '.8125rem', color: '#6b7280' }}>{review.client.name}{review.case ? ` · Caso ${review.case.number}` : ''}</div>}
        </div>
        <button className="pac-btn pac-btn-secondary" onClick={() => exportReport()}>Exportar relatório completo</button>
        <button className="pac-btn pac-btn-secondary" onClick={() => exportReport({ onlyCommented: true })}>Exportar só cláusulas comentadas</button>
      </div>

      {/* Link */}
      <div className="pac-card" style={{ marginBottom: '1rem', background: '#f0f9ff' }}>
        <div style={{ fontSize: '.8125rem', fontWeight: 600, color: '#374151', marginBottom: '.375rem' }}>Link público de revisão</div>
        <div style={{ display: 'flex', gap: '.5rem', alignItems: 'center' }}>
          <input readOnly value={link} style={{ flex: 1, padding: '.5rem .75rem', border: '1.5px solid #bae6fd', borderRadius: 8, fontSize: '.875rem', background: '#fff' }} />
          <button className="pac-btn pac-btn-secondary" onClick={() => navigator.clipboard.writeText(link)}>Copiar</button>
        </div>
      </div>

      {/* Destinatários */}
      <div className="pac-card" style={{ marginBottom: '1.25rem' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '.875rem' }}>
          <div style={{ fontWeight: 700, color: '#374151' }}>Destinatários</div>
          <button className="pac-btn pac-btn-secondary" style={{ fontSize: '.8125rem' }} onClick={() => setAddingRecipient(v => !v)}>+ Adicionar</button>
        </div>
        {addingRecipient && (
          <div style={{ display: 'flex', gap: '.5rem', marginBottom: '.875rem', flexWrap: 'wrap' }}>
            <input className="pac-input" placeholder="Nome do destinatário" value={newRecipName} onChange={e => setNewRecipName(e.target.value)} style={{ flex: '2 1 200px' }} />
            <input className="pac-input" placeholder="Senha (opcional, mín 6)" value={newRecipPwd} onChange={e => setNewRecipPwd(e.target.value)} autoComplete="new-password" style={{ flex: '1 1 150px' }} />
            <button className="pac-btn pac-btn-primary" onClick={handleAddRecipient}>Adicionar</button>
            <button className="pac-btn pac-btn-ghost" onClick={() => { setAddingRecipient(false); setNewRecipPwd(''); }}>Cancelar</button>
          </div>
        )}
        <div style={{ display: 'flex', flexDirection: 'column', gap: '.5rem' }}>
          {accesses.map(acc => (
            <div key={acc.id} style={{ display: 'flex', alignItems: 'center', gap: '1rem', padding: '.625rem .875rem', background: '#f9fafb', borderRadius: 8, flexWrap: 'wrap' }}>
              <div style={{ fontWeight: 600, flex: 1 }}>{acc.recipient_name}</div>
              <code style={{ fontSize: '.8125rem', color: '#374151', background: '#e5e7eb', padding: '2px 8px', borderRadius: 6 }}>{acc.login}</code>
              {statusBadge(acc)}
              {regen[acc.id]
                ? <code style={{ background: '#fef9c3', padding: '2px 8px', borderRadius: 6, fontSize: '.8125rem' }}>Nova senha: {regen[acc.id]}</code>
                : <div style={{ display: 'flex', gap: '.25rem', alignItems: 'center' }}>
                    <input
                      className="pac-input"
                      placeholder="Senha (opcional)"
                      value={regenPwdInput[acc.id] || ''}
                      onChange={e => setRegenPwdInput(prev => ({ ...prev, [acc.id]: e.target.value }))}
                      autoComplete="new-password"
                      style={{ fontSize: '.75rem', padding: '.25rem .5rem', width: 140 }}
                    />
                    <button className="pac-btn pac-btn-ghost" style={{ fontSize: '.75rem' }} onClick={() => handleRegenPassword(acc.id)}>
                      {(regenPwdInput[acc.id] || '').trim() ? 'Definir senha' : 'Gerar senha'}
                    </button>
                  </div>}
              }
            </div>
          ))}
        </div>
      </div>

      {/* Tabela cláusulas × destinatários */}
      <div className="pac-card" style={{ overflowX: 'auto' }}>
        <div style={{ fontWeight: 700, color: '#374151', marginBottom: '1rem' }}>
          Comentários por cláusula ({clauses.length} cláusulas · {accesses.length} destinatário{accesses.length !== 1 ? 's' : ''})
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '.875rem' }}>
          <thead>
            <tr style={{ borderBottom: '2px solid #e5e7eb' }}>
              <th style={{ textAlign: 'left', padding: '.5rem .75rem', color: '#6b7280', fontWeight: 600, width: 200 }}>Cláusula</th>
              {accesses.map(acc => (
                <th key={acc.id} style={{ textAlign: 'center', padding: '.5rem .75rem', color: '#6b7280', fontWeight: 600, minWidth: 120 }}>{acc.recipient_name}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {clauses.map(clause => (
              <React.Fragment key={clause.id}>
                <tr style={{ borderBottom: '1px solid #f3f4f6' }} onClick={() => setExpandedCell(prev => prev === clause.id ? null : clause.id)}>
                  <td style={{ padding: '.625rem .75rem', cursor: 'pointer' }}>
                    {clause.number_label && <span style={{ color: '#9ca3af', fontSize: '.75rem', marginRight: '.375rem' }}>{clause.number_label}.</span>}
                    <span style={{ fontWeight: 500, color: '#111' }}>{clause.title}</span>
                  </td>
                  {accesses.map(acc => {
                    const comment = getComment(clause.id, acc.id);
                    return (
                      <td key={acc.id} style={{ textAlign: 'center', padding: '.625rem .75rem' }}>
                        {commentBadge(comment)}
                      </td>
                    );
                  })}
                </tr>
                {expandedCell === clause.id && (
                  <tr style={{ background: '#f8fafc' }}>
                    <td colSpan={accesses.length + 1} style={{ padding: '1rem .75rem' }}>
                      <div style={{ fontWeight: 600, marginBottom: '.5rem', color: '#374151' }}>
                        {clause.number_label ? `${clause.number_label}. ` : ''}{clause.title}
                      </div>
                      {accesses.map(acc => {
                        const comment = getComment(clause.id, acc.id);
                        if (!comment) return <div key={acc.id} style={{ fontSize: '.8125rem', color: '#9ca3af', marginBottom: '.375rem' }}><strong>{acc.recipient_name}:</strong> sem comentário</div>;
                        return (
                          <div key={acc.id} style={{ marginBottom: '.625rem', padding: '.625rem .875rem', background: '#fff', borderRadius: 8, border: '1px solid #e5e7eb' }}>
                            <div style={{ fontWeight: 600, fontSize: '.8125rem', color: '#374151', marginBottom: '.25rem' }}>{acc.recipient_name} — {commentBadge(comment)}</div>
                            {comment.content && <div style={{ color: '#374151', fontSize: '.875rem' }}>{comment.content}</div>}
                          </div>
                        );
                      })}
                    </td>
                  </tr>
                )}
              </React.Fragment>
            ))}
          </tbody>
        </table>
      </div>

      {/* Toast */}
      {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.ContratosRevisao = ContratosRevisao;
