// PAC Sistema — Propostas (Kanban + geração de proposta + criar tarefa)
// Porte do app `contratos/` (PAC Propostas) para o front padrão do PAC.
// Template e prompts ficam no backend (intactos); aqui é só experiência/UI.

const RESPONSIBLES = ['Fernando Peracini', 'Fernanda Alves da Silva', 'Paula Cottas'];

// Colunas do Kanban pedidas: Novas · Enviadas · Follow Up · Aceitas · Rejeitadas
const PROP_COLUMNS = [
  { id: 'novas',      label: 'Novas',     status: 'rascunho',    accent: '#8B5CF6', match: ['rascunho'] },
  { id: 'enviadas',   label: 'Enviadas',  status: 'enviada',     accent: '#3B82F6', match: ['enviada'] },
  { id: 'followup',   label: 'Follow Up', status: 'visualizada', accent: '#E8A33D', match: ['visualizada', 'standby'] },
  { id: 'aceitas',    label: 'Aceitas',   status: 'aceita',      accent: '#3DA35D', match: ['aceita'] },
  { id: 'rejeitadas', label: 'Rejeitadas',status: 'recusada',    accent: '#C2253E', match: ['recusada'] },
];

const STATUS_TO_COLUMN = {};
PROP_COLUMNS.forEach(c => c.match.forEach(s => { STATUS_TO_COLUMN[s] = c.id; }));

const STATUS_LABEL = {
  rascunho: 'Rascunho', enviada: 'Enviada', visualizada: 'Visualizada',
  aceita: 'Aceita', recusada: 'Recusada', standby: 'Stand-by',
};

const fmtDate = (s) => {
  if (!s) return '';
  try { return new Date(s).toLocaleDateString('pt-BR', { day: '2-digit', month: 'short' }); }
  catch { return ''; }
};

// ============================================================
// Card da proposta
// ============================================================
const PropostaCard = ({ p, accent, onOpen, onDragStart, onCreateTask }) => {
  const hasAlert = p.first_opened_at && !p.notification_read;
  return (
    <div
      className="kb-card"
      draggable
      onDragStart={(e) => onDragStart(e, p)}
      onClick={() => onOpen(p)}
      style={{
        background: '#fff',
        border: '1px solid var(--border, #e8e8f0)',
        borderLeft: `3px solid ${accent}`,
        borderRadius: 8,
        padding: '11px 13px',
        marginBottom: 8,
        cursor: 'pointer',
        boxShadow: hasAlert ? '0 0 0 2px var(--pac-neon, #C8FF00)' : '0 1px 2px rgba(13,13,107,.04)',
        transition: 'box-shadow .15s, transform .1s',
      }}
    >
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8 }}>
        <span style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--pac-navy, #0D0D6B)', letterSpacing: '.02em' }}>
          {p.proposal_number}
        </span>
        {hasAlert && <span title="Aberta pelo cliente" style={{ fontSize: 9, fontWeight: 700, color: 'var(--pac-navy,#0D0D6B)', background: 'var(--pac-neon,#C8FF00)', padding: '1px 6px', borderRadius: 4 }}>ABRIU</span>}
      </div>
      <div style={{ fontSize: 13, fontWeight: 600, color: '#1a1a2e', marginTop: 4, lineHeight: 1.3 }}>
        {p.client_name}
      </div>
      {p.case_title && (
        <div style={{ fontSize: 11, color: 'var(--fg-muted, #888)', marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {p.case_title}
        </div>
      )}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 8 }}>
        <span style={{ fontSize: 12, fontWeight: 700, color: 'var(--pac-navy,#0D0D6B)' }}>{p.total_value || '—'}</span>
        <span style={{ fontSize: 10.5, color: 'var(--fg-muted,#999)' }}>{fmtDate(p.created_at)}</span>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 6 }}>
        <span style={{ fontSize: 10.5, color: 'var(--fg-muted,#999)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {(p.responsible || '').split(' ')[0]}
        </span>
        <button
          onClick={(e) => { e.stopPropagation(); onCreateTask(p); }}
          title="Criar tarefa principal a partir desta proposta"
          style={{ fontSize: 10.5, fontWeight: 600, color: 'var(--pac-navy,#0D0D6B)', background: 'transparent', border: '1px solid var(--border,#e0e0ea)', borderRadius: 5, padding: '2px 7px', cursor: 'pointer' }}
        >
          + Tarefa
        </button>
      </div>
    </div>
  );
};

// ============================================================
// Coluna do Kanban
// ============================================================
const PropostaColumn = ({ col, items, onOpen, onDragStart, onDrop, onCreateTask, dragOver }) => (
  <div
    onDragOver={(e) => { e.preventDefault(); }}
    onDrop={(e) => onDrop(e, col)}
    style={{
      flex: '1 1 0',
      minWidth: 220,
      background: dragOver ? 'rgba(200,255,0,.06)' : 'var(--bg-subtle, #f4f4f8)',
      borderRadius: 10,
      padding: 10,
      display: 'flex',
      flexDirection: 'column',
      outline: dragOver ? '2px dashed var(--pac-neon,#C8FF00)' : 'none',
    }}
  >
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10, paddingLeft: 2 }}>
      <span style={{ width: 8, height: 8, borderRadius: '50%', background: col.accent }} />
      <span style={{ fontSize: 12, fontWeight: 700, color: '#1a1a2e' }}>{col.label}</span>
      <span style={{ fontSize: 11, color: 'var(--fg-muted,#999)', background: '#fff', borderRadius: 10, padding: '0 7px', minWidth: 20, textAlign: 'center' }}>
        {items.length}
      </span>
    </div>
    <div style={{ flex: 1, minHeight: 40 }}>
      {items.map(p => (
        <PropostaCard key={p.id} p={p} accent={col.accent} onOpen={onOpen} onDragStart={onDragStart} onCreateTask={onCreateTask} />
      ))}
      {items.length === 0 && (
        <div style={{ fontSize: 11, color: 'var(--fg-muted,#bbb)', textAlign: 'center', padding: '16px 0' }}>—</div>
      )}
    </div>
  </div>
);

// ============================================================
// Modal: nova proposta (geração via IA a partir de contexto)
// ============================================================
const GenerateModal = ({ onClose, onGenerated }) => {
  React.useEffect(() => {
    const h = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', h);
    return () => document.removeEventListener('keydown', h);
  }, [onClose]);
  const [context, setContext] = React.useState('');
  const [responsible, setResponsible] = React.useState(RESPONSIBLES[0]);
  const [clientName, setClientName] = React.useState('');
  const [clientCity, setClientCity] = React.useState('');
  const [feeAmount, setFeeAmount] = React.useState('');
  const [validity, setValidity] = React.useState(10);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');

  const submit = async () => {
    if (context.trim().length < 10) { setError('Descreva o caso com pelo menos 10 caracteres.'); return; }
    setLoading(true); setError('');
    try {
      const res = await window.PACApi.propostas.generate({
        context_text: context,
        responsible,
        validity_days: Number(validity) || 10,
        client_name: clientName || undefined,
        client_city: clientCity || undefined,
        fee_amount: feeAmount || undefined,
      });
      onGenerated(res.id);
    } catch (err) {
      setError(err.message || 'Erro ao gerar proposta.');
    } finally {
      setLoading(false);
    }
  };

  const lbl = { display: 'block', fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.06em', color: '#666', marginBottom: 5 };
  const inp = { width: '100%', boxSizing: 'border-box', padding: '9px 11px', border: '1.5px solid #ddd', borderRadius: 7, fontSize: 13, color: '#1a1a2e', outline: 'none' };

  return (
    <div className="scrim" onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(26,10,46,.5)', zIndex: 400, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: '#fff', borderRadius: 14, width: '100%', maxWidth: 560, maxHeight: '90vh', overflow: 'auto', padding: 24, boxShadow: '0 20px 60px rgba(0,0,0,.3)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          <h2 style={{ fontSize: 18, fontWeight: 800, color: 'var(--pac-navy,#0D0D6B)', fontFamily: 'Georgia, serif', margin: 0 }}>Nova proposta</h2>
          <button onClick={onClose} style={{ border: 0, background: 'transparent', fontSize: 22, color: '#999', cursor: 'pointer', lineHeight: 1 }}>×</button>
        </div>

        <div style={{ marginBottom: 14 }}>
          <label style={lbl}>Contexto do caso</label>
          <textarea
            value={context}
            onChange={(e) => setContext(e.target.value)}
            placeholder="Descreva o cliente, o caso, o objetivo e quaisquer detalhes. A IA gera a proposta no padrão PAC."
            rows={5}
            autoFocus
            style={{ ...inp, resize: 'vertical', fontFamily: 'inherit' }}
          />
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 14 }}>
          <div>
            <label style={lbl}>Responsável</label>
            <select value={responsible} onChange={(e) => setResponsible(e.target.value)} style={inp}>
              {RESPONSIBLES.map(r => <option key={r} value={r}>{r}</option>)}
            </select>
          </div>
          <div>
            <label style={lbl}>Validade (dias)</label>
            <input type="number" min={1} value={validity} onChange={(e) => setValidity(e.target.value)} style={inp} />
          </div>
          <div>
            <label style={lbl}>Cliente (opcional)</label>
            <input value={clientName} onChange={(e) => setClientName(e.target.value)} placeholder="Nome / empresa" style={inp} />
          </div>
          <div>
            <label style={lbl}>Cidade (opcional)</label>
            <input value={clientCity} onChange={(e) => setClientCity(e.target.value)} placeholder="Cidade, UF" style={inp} />
          </div>
          <div>
            <label style={lbl}>Honorários (opcional)</label>
            <input value={feeAmount} onChange={(e) => setFeeAmount(e.target.value)} placeholder="ex: 5.000,00" style={inp} />
          </div>
        </div>

        {error && <div style={{ padding: '9px 12px', borderRadius: 6, fontSize: 12.5, background: 'rgba(194,37,62,.07)', border: '1px solid rgba(194,37,62,.2)', color: '#C2253E', marginBottom: 12 }}>{error}</div>}

        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
          <button onClick={onClose} className="btn ghost" style={{ padding: '10px 16px', borderRadius: 8, border: '1px solid #ddd', background: '#fff', cursor: 'pointer', fontSize: 13, fontWeight: 600 }}>Cancelar</button>
          <button onClick={submit} disabled={loading} style={{ padding: '10px 18px', borderRadius: 8, border: 0, background: loading ? '#555' : 'var(--pac-navy,#0D0D6B)', color: '#fff', cursor: loading ? 'not-allowed' : 'pointer', fontSize: 13, fontWeight: 700, display: 'flex', alignItems: 'center', gap: 8 }}>
            {loading ? <><span className="spinner" style={{ width: 13, height: 13, borderColor: 'rgba(255,255,255,.25)', borderTopColor: '#fff' }} /> Gerando…</> : 'Gerar proposta'}
          </button>
        </div>
      </div>
    </div>
  );
};

// ============================================================
// Drawer de detalhe da proposta
// ============================================================
const PropostaDrawer = ({ id, onClose, onChanged, onCreateTask }) => {
  React.useEffect(() => {
    const h = (e) => { if (e.key === 'Escape' && !editMode) onClose(); };
    document.addEventListener('keydown', h);
    return () => document.removeEventListener('keydown', h);
  }, [onClose]);
  const [p, setP] = React.useState(null);
  const [tab, setTab] = React.useState('preview');
  const [link, setLink] = React.useState(null);
  const [notes, setNotes] = React.useState([]);
  const [noteText, setNoteText] = React.useState('');
  const [refineText, setRefineText] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [flash, setFlash] = React.useState('');
  const [editMode, setEditMode] = React.useState(false);
  const [confirmDelete, setConfirmDelete] = React.useState(false);
  const iframeRef = React.useRef(null);

  const load = React.useCallback(async () => {
    const prop = await window.PACApi.propostas.get(id);
    setP(prop);
  }, [id]);

  React.useEffect(() => { load(); }, [load]);
  React.useEffect(() => {
    if (tab === 'rastreio') window.PACApi.propostas.activeLink(id).then(setLink).catch(() => {});
    if (tab === 'notas') window.PACApi.propostas.listNotes(id).then(setNotes).catch(() => {});
  }, [tab, id]);

  const showFlash = (msg) => { setFlash(msg); setTimeout(() => setFlash(''), 2500); };

  const doDelete = async () => {
    if (!confirmDelete) { setConfirmDelete(true); setTimeout(() => setConfirmDelete(false), 4000); return; }
    setBusy(true);
    try {
      await window.PACApi.propostas.remove(id);
      onChanged && onChanged();
      onClose();
    } catch (e) {
      showFlash('Erro ao excluir: ' + e.message);
      setConfirmDelete(false);
    } finally {
      setBusy(false);
    }
  };

  const doLink = async () => {
    setBusy(true);
    try {
      const res = await window.PACApi.propostas.generateLink(id);
      try { await navigator.clipboard.writeText(res.url); } catch (e) {}
      showFlash('Link gerado e copiado: ' + res.url);
      await load(); onChanged && onChanged();
    } catch (e) { showFlash('Erro: ' + e.message); } finally { setBusy(false); }
  };

  const doRefine = async () => {
    if (refineText.trim().length < 5) return;
    setBusy(true);
    try {
      await window.PACApi.propostas.refine(id, refineText);
      setRefineText('');
      showFlash('Proposta ajustada pela IA.');
      await load();
    } catch (e) { showFlash('Erro: ' + e.message); } finally { setBusy(false); }
  };

  const doAddNote = async () => {
    if (!noteText.trim()) return;
    const n = await window.PACApi.propostas.addNote(id, noteText);
    setNotes([n, ...notes]); setNoteText('');
  };

  const doCreateTask = async () => {
    setBusy(true);
    try { await onCreateTask(p); showFlash('Tarefa principal criada no Kanban de Tarefas.'); }
    finally { setBusy(false); }
  };

  const buildEditSrcDoc = (html) => {
    if (!html) return html;
    const script = `<script data-pac-edit="1">
      document.addEventListener('DOMContentLoaded', function() {
        document.body.contentEditable = 'true';
        document.body.style.outline = 'none';
        document.body.style.cursor = 'text';
        var toolbar = document.querySelector('.toolbar');
        if (toolbar) toolbar.style.display = 'none';
      });
    <\/script>`;
    return /<\/body>/i.test(html)
      ? html.replace(/<\/body>/i, script + '</body>')
      : html + script;
  };

  const doSaveHtml = async () => {
    if (!iframeRef.current) return;
    setBusy(true);
    try {
      const doc = iframeRef.current.contentDocument;
      if (!doc) throw new Error('Não foi possível acessar o documento.');
      // Remove scripts de edição (por atributo ou por conteúdo)
      doc.querySelectorAll('script').forEach(function(s) {
        if (s.getAttribute('data-pac-edit') || (s.textContent && s.textContent.indexOf('contentEditable') !== -1)) {
          s.parentNode && s.parentNode.removeChild(s);
        }
      });
      // Reseta estado de edição do body
      if (doc.body) {
        doc.body.removeAttribute('contenteditable');
        doc.body.style.outline = '';
        doc.body.style.cursor = '';
      }
      const html = '<!DOCTYPE html>' + doc.documentElement.outerHTML;
      await window.PACApi.propostas.saveHtml(id, html);
      showFlash('Prévia salva. O link do cliente foi atualizado.');
      setEditMode(false);
      await load();
      onChanged && onChanged();
    } catch (e) {
      showFlash('Erro ao salvar: ' + e.message);
    } finally {
      setBusy(false);
    }
  };

  const tabBtn = (key, label) => (
    <button onClick={() => setTab(key)} style={{ padding: '8px 12px', border: 0, borderBottom: tab === key ? '2px solid var(--pac-navy,#0D0D6B)' : '2px solid transparent', background: 'transparent', cursor: 'pointer', fontSize: 12.5, fontWeight: tab === key ? 700 : 500, color: tab === key ? 'var(--pac-navy,#0D0D6B)' : '#888' }}>{label}</button>
  );

  return (
    <div className="scrim" onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(26,10,46,.45)', zIndex: 380, display: 'flex', justifyContent: 'flex-end' }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: 'min(640px, 96vw)', height: '100%', background: '#fff', display: 'flex', flexDirection: 'column', boxShadow: '-12px 0 40px rgba(0,0,0,.18)' }}>
        {!p ? (
          <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, color: '#999' }}>
            <span className="spinner" style={{ borderColor: 'rgba(13,13,107,.15)', borderTopColor: 'var(--pac-navy,#0D0D6B)' }} /> Carregando…
          </div>
        ) : (
          <>
            <div style={{ padding: '18px 20px', borderBottom: '1px solid #eee' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                <div>
                  <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--pac-navy,#0D0D6B)' }}>{p.proposal_number}</div>
                  <div style={{ fontSize: 18, fontWeight: 800, color: '#1a1a2e', fontFamily: 'Georgia, serif' }}>{p.client_name}</div>
                  <div style={{ fontSize: 12, color: '#888', marginTop: 2 }}>
                    {STATUS_LABEL[p.status] || p.status} · {p.responsible} · {p.total_value || '—'}
                  </div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
                  <button
                    onClick={doDelete}
                    disabled={busy}
                    style={{
                      padding: '5px 11px', borderRadius: 6, fontSize: 11.5, fontWeight: 700,
                      cursor: busy ? 'not-allowed' : 'pointer',
                      border: confirmDelete ? 0 : '1px solid #C2253E',
                      background: confirmDelete ? '#C2253E' : 'transparent',
                      color: confirmDelete ? '#fff' : '#C2253E',
                      transition: 'all .15s',
                    }}
                  >
                    {confirmDelete ? 'Confirmar exclusão' : 'Excluir'}
                  </button>
                  <button onClick={onClose} style={{ border: 0, background: 'transparent', fontSize: 24, color: '#999', cursor: 'pointer', lineHeight: 1 }}>×</button>
                </div>
              </div>
              <div style={{ display: 'flex', gap: 8, marginTop: 14, flexWrap: 'wrap' }}>
                {!editMode && (
                  <>
                    <a href={window.PACApi.propostas.pdfUrl(p.id)} target="_blank" rel="noreferrer" style={{ textDecoration: 'none', padding: '7px 13px', borderRadius: 7, background: 'var(--pac-navy,#0D0D6B)', color: '#fff', fontSize: 12, fontWeight: 700 }}>Baixar PDF</a>
                    <button onClick={doLink} disabled={busy} style={{ padding: '7px 13px', borderRadius: 7, background: 'var(--pac-neon,#C8FF00)', color: 'var(--pac-navy,#0D0D6B)', border: 0, fontSize: 12, fontWeight: 700, cursor: 'pointer' }}>Gerar link & enviar</button>
                    <button onClick={doCreateTask} disabled={busy} style={{ padding: '7px 13px', borderRadius: 7, background: '#fff', color: 'var(--pac-navy,#0D0D6B)', border: '1px solid var(--pac-navy,#0D0D6B)', fontSize: 12, fontWeight: 700, cursor: 'pointer' }}>+ Criar tarefa</button>
                    {p.generated_html && (
                      <button onClick={() => { setTab('preview'); setEditMode(true); }} style={{ padding: '7px 13px', borderRadius: 7, background: '#fff', color: '#555', border: '1px solid #ddd', fontSize: 12, fontWeight: 700, cursor: 'pointer' }}>✏️ Editar prévia</button>
                    )}
                  </>
                )}
                {editMode && (
                  <>
                    <button onClick={doSaveHtml} disabled={busy} style={{ padding: '7px 16px', borderRadius: 7, background: '#3DA35D', color: '#fff', border: 0, fontSize: 12, fontWeight: 700, cursor: busy ? 'not-allowed' : 'pointer' }}>
                      {busy ? 'Salvando…' : '💾 Salvar alterações'}
                    </button>
                    <button onClick={() => setEditMode(false)} disabled={busy} style={{ padding: '7px 13px', borderRadius: 7, background: '#fff', color: '#888', border: '1px solid #ddd', fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>Cancelar</button>
                    <span style={{ fontSize: 11, color: '#e8713c', alignSelf: 'center', fontWeight: 600 }}>✏️ Modo edição ativo — clique no texto para editar</span>
                  </>
                )}
              </div>
              {flash && <div style={{ marginTop: 10, fontSize: 11.5, color: 'var(--pac-navy,#0D0D6B)', background: 'rgba(200,255,0,.18)', borderRadius: 6, padding: '7px 10px', wordBreak: 'break-all' }}>{flash}</div>}
            </div>

            <div style={{ display: 'flex', gap: 4, padding: '0 16px', borderBottom: '1px solid #eee' }}>
              {tabBtn('preview', 'Pré-visualização')}
              {tabBtn('rastreio', 'Rastreio')}
              {tabBtn('notas', 'Notas')}
              {tabBtn('ia', 'Ajustar com IA')}
            </div>

            <div style={{ flex: 1, overflow: 'auto', background: '#f4f4f8' }}>
              {tab === 'preview' && (
                p.generated_html ? (
                  <div style={{ position: 'relative', width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
                    {editMode && (
                      <div style={{ padding: '6px 12px', background: '#fffbe6', borderBottom: '1px solid #f0c020', fontSize: 11.5, color: '#7a5800', display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
                        <span>Clique em qualquer texto para editar diretamente. Clique em &quot;Salvar alterações&quot; para publicar.</span>
                      </div>
                    )}
                    <iframe
                      ref={iframeRef}
                      key={editMode ? 'edit' : 'view'}
                      title="preview"
                      srcDoc={editMode ? buildEditSrcDoc(p.generated_html) : p.generated_html}
                      style={{ flex: 1, border: 0, background: '#222' }}
                    />
                  </div>
                ) : (
                  <div style={{ padding: 24, color: '#888', fontSize: 13 }}>Esta proposta não tem HTML gerado. Use "Baixar PDF" para ver o documento renderizado, ou regenere pela IA.</div>
                )
              )}

              {tab === 'rastreio' && (
                <div style={{ padding: 20 }}>
                  <RastreioPanel id={id} link={link} onGenerateLink={doLink} />
                </div>
              )}

              {tab === 'notas' && (
                <div style={{ padding: 20 }}>
                  <div style={{ display: 'flex', gap: 8, marginBottom: 14 }}>
                    <input value={noteText} onChange={(e) => setNoteText(e.target.value)} placeholder="Adicionar nota interna…" onKeyDown={(e) => e.key === 'Enter' && doAddNote()} style={{ flex: 1, padding: '9px 11px', border: '1.5px solid #ddd', borderRadius: 7, fontSize: 13, outline: 'none' }} />
                    <button onClick={doAddNote} style={{ padding: '9px 14px', borderRadius: 7, border: 0, background: 'var(--pac-navy,#0D0D6B)', color: '#fff', fontWeight: 700, fontSize: 12.5, cursor: 'pointer' }}>Salvar</button>
                  </div>
                  {notes.length === 0 && <div style={{ color: '#999', fontSize: 12.5 }}>Sem notas ainda.</div>}
                  {notes.map(n => (
                    <div key={n.id} style={{ background: '#fff', border: '1px solid #eee', borderRadius: 8, padding: '10px 12px', marginBottom: 8 }}>
                      <div style={{ fontSize: 13, color: '#1a1a2e' }}>{n.content}</div>
                      <div style={{ fontSize: 10.5, color: '#aaa', marginTop: 4 }}>{n.users?.name || ''} · {fmtDate(n.created_at)}</div>
                    </div>
                  ))}
                </div>
              )}

              {tab === 'ia' && (
                <div style={{ padding: 20 }}>
                  <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: '#666', marginBottom: 6 }}>Instrução de ajuste</label>
                  <textarea value={refineText} onChange={(e) => setRefineText(e.target.value)} rows={4} placeholder="ex: deixe os honorários em 3 parcelas e reforce o ponto de urgência." style={{ width: '100%', boxSizing: 'border-box', padding: '10px 12px', border: '1.5px solid #ddd', borderRadius: 8, fontSize: 13, resize: 'vertical', fontFamily: 'inherit', outline: 'none' }} />
                  <button onClick={doRefine} disabled={busy} style={{ marginTop: 10, padding: '9px 16px', borderRadius: 8, border: 0, background: busy ? '#555' : 'var(--pac-navy,#0D0D6B)', color: '#fff', fontWeight: 700, fontSize: 12.5, cursor: busy ? 'not-allowed' : 'pointer' }}>
                    {busy ? 'Ajustando…' : 'Aplicar ajuste'}
                  </button>
                  <p style={{ fontSize: 11.5, color: '#999', marginTop: 10, lineHeight: 1.5 }}>A IA reescreve apenas os campos pedidos e re-renderiza o documento no template PAC.</p>
                </div>
              )}
            </div>
          </>
        )}
      </div>
    </div>
  );
};

const RastreioPanel = ({ id, link, onGenerateLink }) => {
  const [a, setA] = React.useState(null);
  React.useEffect(() => { window.PACApi.propostas.analytics(id).then(setA).catch(() => {}); }, [id]);
  const box = { background: '#fff', border: '1px solid #eee', borderRadius: 8, padding: '12px 14px', flex: 1 };
  return (
    <div>
      <div style={{ marginBottom: 14 }}>
        <div style={{ fontSize: 11, fontWeight: 700, color: '#666', textTransform: 'uppercase', letterSpacing: '.06em', marginBottom: 6 }}>Link público</div>
        {link
          ? <div style={{ fontSize: 12.5, color: 'var(--pac-navy,#0D0D6B)', wordBreak: 'break-all' }}>/p/{link.token} <span style={{ color: '#aaa' }}>(expira {fmtDate(link.expires_at)})</span></div>
          : <button onClick={onGenerateLink} style={{ padding: '7px 13px', borderRadius: 7, background: 'var(--pac-neon,#C8FF00)', color: 'var(--pac-navy,#0D0D6B)', border: 0, fontSize: 12, fontWeight: 700, cursor: 'pointer' }}>Gerar link público</button>}
      </div>
      <div style={{ display: 'flex', gap: 10 }}>
        <div style={box}><div style={{ fontSize: 22, fontWeight: 800, color: 'var(--pac-navy,#0D0D6B)' }}>{a?.totalViews ?? 0}</div><div style={{ fontSize: 11, color: '#888' }}>Aberturas</div></div>
        <div style={box}><div style={{ fontSize: 22, fontWeight: 800, color: 'var(--pac-navy,#0D0D6B)' }}>{a ? Math.round((a.totalTimeMs || 0) / 1000) : 0}s</div><div style={{ fontSize: 11, color: '#888' }}>Tempo total</div></div>
        <div style={box}><div style={{ fontSize: 13, fontWeight: 800, color: 'var(--pac-navy,#0D0D6B)', marginTop: 4 }}>{a?.action || 'nenhuma'}</div><div style={{ fontSize: 11, color: '#888' }}>Ação do cliente</div></div>
      </div>
      {a?.acceptedBy && <div style={{ marginTop: 12, fontSize: 12.5, color: '#3DA35D' }}>Aceita por <b>{a.acceptedBy}</b>.</div>}
    </div>
  );
};

// ============================================================
// View principal
// ============================================================
const Propostas = ({ currentUser }) => {
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [search, setSearch] = React.useState('');
  const [genOpen, setGenOpen] = React.useState(false);
  const [openId, setOpenId] = React.useState(null);
  const [dragId, setDragId] = React.useState(null);
  const [dragOverCol, setDragOverCol] = React.useState(null);
  const [flash, setFlash] = React.useState('');

  const load = React.useCallback(async () => {
    setLoading(true);
    try { setItems(await window.PACApi.propostas.list()); }
    catch (e) { /* silencioso */ }
    finally { setLoading(false); }
  }, []);

  React.useEffect(() => { load(); }, [load]);

  const showFlash = (m) => { setFlash(m); setTimeout(() => setFlash(''), 3000); };

  const filtered = items.filter(p =>
    !search || (p.client_name + ' ' + p.proposal_number + ' ' + (p.case_title || '')).toLowerCase().includes(search.toLowerCase())
  );

  const byColumn = (colId) => filtered.filter(p => (STATUS_TO_COLUMN[p.status] || 'novas') === colId);

  const onDragStart = (e, p) => { setDragId(p.id); try { e.dataTransfer.setData('text/plain', p.id); } catch (x) {} };

  const onDrop = async (e, col) => {
    e.preventDefault();
    setDragOverCol(null);
    const id = dragId || (e.dataTransfer && e.dataTransfer.getData('text/plain'));
    setDragId(null);
    if (!id) return;
    const p = items.find(x => x.id === id);
    if (!p) return;
    if ((STATUS_TO_COLUMN[p.status] || 'novas') === col.id) return; // já está na coluna
    // Otimista
    setItems(prev => prev.map(x => x.id === id ? { ...x, status: col.status } : x));
    try { await window.PACApi.propostas.setStatus(id, col.status); }
    catch (err) { showFlash('Erro ao mover: ' + err.message); load(); }
  };

  const handleCreateTask = async (p) => {
    try {
      await window.PACApi.propostas.createTask(p.id);
      showFlash(`Tarefa principal criada para ${p.client_name}.`);
    } catch (e) { showFlash('Erro ao criar tarefa: ' + e.message); }
  };

  return (
    <div style={{ padding: '20px 24px', height: '100%', display: 'flex', flexDirection: 'column', boxSizing: 'border-box' }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 16, flexWrap: 'wrap' }}>
        <div>
          <h1 style={{ fontSize: 20, fontWeight: 800, color: 'var(--pac-navy,#0D0D6B)', fontFamily: 'Georgia, serif', margin: 0 }}>Propostas</h1>
          <p style={{ fontSize: 12.5, color: '#888', margin: '2px 0 0' }}>Pipeline comercial · gere, acompanhe e converta em tarefas</p>
        </div>
        <div style={{ flex: 1 }} />
        <input
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="Buscar por cliente, número…"
          style={{ padding: '9px 13px', border: '1.5px solid #ddd', borderRadius: 8, fontSize: 13, width: 240, maxWidth: '50vw', outline: 'none' }}
        />
        <button onClick={() => setGenOpen(true)} style={{ padding: '10px 16px', borderRadius: 8, border: 0, background: 'var(--pac-navy,#0D0D6B)', color: '#fff', fontWeight: 700, fontSize: 13, cursor: 'pointer' }}>+ Nova proposta</button>
      </div>

      {flash && <div style={{ marginBottom: 12, fontSize: 12.5, color: 'var(--pac-navy,#0D0D6B)', background: 'rgba(200,255,0,.2)', borderRadius: 7, padding: '9px 12px' }}>{flash}</div>}

      {loading ? (
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, color: '#999' }}>
          <span className="spinner" style={{ borderColor: 'rgba(13,13,107,.15)', borderTopColor: 'var(--pac-navy,#0D0D6B)' }} /> Carregando propostas…
        </div>
      ) : (
        <div style={{ flex: 1, display: 'flex', gap: 12, overflowX: 'auto', alignItems: 'stretch', paddingBottom: 8 }}>
          {PROP_COLUMNS.map(col => (
            <div key={col.id}
              onDragEnter={() => setDragOverCol(col.id)}
              onDragLeave={(e) => { if (e.currentTarget === e.target) setDragOverCol(null); }}
              style={{ display: 'flex', flex: '1 1 0', minWidth: 220 }}
            >
              <PropostaColumn
                col={col}
                items={byColumn(col.id)}
                onOpen={(p) => setOpenId(p.id)}
                onDragStart={onDragStart}
                onDrop={onDrop}
                onCreateTask={handleCreateTask}
                dragOver={dragOverCol === col.id}
              />
            </div>
          ))}
        </div>
      )}

      {genOpen && (
        <GenerateModal
          onClose={() => setGenOpen(false)}
          onGenerated={(id) => { setGenOpen(false); load(); setOpenId(id); }}
        />
      )}

      {openId && (
        <PropostaDrawer
          id={openId}
          onClose={() => { setOpenId(null); load(); }}
          onChanged={load}
          onCreateTask={handleCreateTask}
        />
      )}
    </div>
  );
};

window.Propostas = Propostas;
