// ─────────────────────────────────────────────────────────────────────────────
// Artigos — recepção → aprovação → agendamento → publicação no site.
// Duas abas: "Para Aprovar" (cards de artigos do Manus) e "Enviar para o Manus".
// ─────────────────────────────────────────────────────────────────────────────

const ARTIGO_AREAS = [
  { slug: 'contratual',  label: 'Contratual',              color: '#0D0D6B' },
  { slug: 'societario',  label: 'Societário',              color: '#4c1d95' },
  { slug: 'civel',       label: 'Cível',                   color: '#1e5f9e' },
  { slug: 'trabalhista', label: 'Trabalhista',             color: '#b7791f' },
  { slug: 'tributario',  label: 'Tributário',              color: '#2f855a' },
  { slug: 'sucessorio',  label: 'Planejamento Sucessório', color: '#805ad5' },
  { slug: 'familia',     label: 'Família',                 color: '#c05621' },
];
const AREA_META = Object.fromEntries(ARTIGO_AREAS.map(a => [a.slug, a]));
const areaLabel = (slug) => AREA_META[slug]?.label || slug;

const ORIGEM_LABELS = { manus: 'Manus', manual: 'Manual', claude_code: 'Claude Code' };
const origemLabel = (origem) => ORIGEM_LABELS[origem] || origem;
const areaColor = (slug) => AREA_META[slug]?.color || '#555';

const ARTIGO_STATUS = {
  pendente_aprovacao: { label: 'Pendente',   color: '#b7791f', bg: '#fdf6e3' },
  em_revisao:         { label: 'Em revisão', color: '#805ad5', bg: '#f3edfb' },
  agendado:           { label: 'Agendado',   color: '#1e5f9e', bg: '#e8f1fb' },
  publicado:          { label: 'Publicado',  color: '#2f855a', bg: '#e9f7ef' },
  rejeitado:          { label: 'Rejeitado',  color: '#8a8a8a', bg: '#f0f0f2' },
  erro_publicacao:    { label: 'Erro',       color: '#C2253E', bg: '#fdeef0' },
};

// ── Sanitização defensiva do HTML antes de renderizar (anti stored-XSS interno) ──
function sanitizeArtigoHtml(html) {
  if (!html) return '';
  let out = String(html);
  out = out.replace(/<\s*(script|style|iframe|object|embed|link|meta)\b[\s\S]*?<\s*\/\s*\1\s*>/gi, '');
  out = out.replace(/<\s*(script|style|iframe|object|embed|link|meta)\b[^>]*>/gi, '');
  out = out.replace(/\son\w+\s*=\s*"[^"]*"/gi, '');
  out = out.replace(/\son\w+\s*=\s*'[^']*'/gi, '');
  out = out.replace(/\son\w+\s*=\s*[^\s>]+/gi, '');
  out = out.replace(/(href|src)\s*=\s*("|')\s*javascript:[^"']*\2/gi, '$1="#"');
  return out;
}

function artigoPlainText(html, max) {
  const tmp = document.createElement('div');
  tmp.innerHTML = sanitizeArtigoHtml(html);
  const text = (tmp.textContent || tmp.innerText || '').replace(/\s+/g, ' ').trim();
  return max && text.length > max ? text.slice(0, max).trim() + '…' : text;
}

const fmtDate = (iso) => {
  if (!iso) return '—';
  try { return new Date(iso).toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit', year: 'numeric' }); }
  catch { return '—'; }
};
const fmtDateTime = (iso) => {
  if (!iso) return '—';
  try { return new Date(iso).toLocaleString('pt-BR', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' }); }
  catch { return '—'; }
};
// ISO (com offset) → valor para <input type="datetime-local"> na hora local
const toLocalInput = (iso) => {
  const d = iso ? new Date(iso) : new Date();
  const pad = (n) => String(n).padStart(2, '0');
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
};

// ============================================================
// Badges
// ============================================================
const AreaBadge = ({ area }) => (
  <span style={{
    fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.04em',
    padding: '3px 9px', borderRadius: 20, color: '#fff', background: areaColor(area), whiteSpace: 'nowrap',
  }}>{areaLabel(area)}</span>
);
const StatusBadge = ({ status }) => {
  const s = ARTIGO_STATUS[status] || { label: status, color: '#555', bg: '#eee' };
  return (
    <span style={{
      fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.04em',
      padding: '3px 9px', borderRadius: 6, color: s.color, background: s.bg, whiteSpace: 'nowrap',
    }}>{s.label}</span>
  );
};

// ============================================================
// Modal genérico
// ============================================================
const ArtigoModal = ({ title, onClose, children, width = 560 }) => (
  <div
    onClick={onClose}
    style={{ position: 'fixed', inset: 0, background: 'rgba(26,10,46,.55)', zIndex: 400, display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: '48px 16px', overflowY: 'auto' }}
  >
    <div
      onClick={(e) => e.stopPropagation()}
      style={{ background: '#fff', borderRadius: 14, width: '100%', maxWidth: width, boxShadow: '0 32px 80px rgba(13,13,107,.35)' }}
    >
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '18px 22px', borderBottom: '1px solid var(--border)' }}>
        <h3 style={{ margin: 0, fontSize: 16, fontWeight: 700, color: 'var(--pac-navy)', fontFamily: 'Georgia, serif' }}>{title}</h3>
        <button className="tb-ic-btn" onClick={onClose} title="Fechar"><Icon name="x" size={18} /></button>
      </div>
      <div style={{ padding: '20px 22px' }}>{children}</div>
    </div>
  </div>
);

const inputStyle = { width: '100%', boxSizing: 'border-box', padding: '9px 12px', border: '1.5px solid var(--border)', borderRadius: 8, fontSize: 13.5, color: 'var(--pac-black)', outline: 'none', background: '#fff' };
const labelStyle = { display: 'block', marginBottom: 6, fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.06em', color: '#666' };

// ============================================================
// Editor de fontes (lista dinâmica {titulo, url})
// ============================================================
const FontesEditor = ({ fontes, onChange }) => {
  const list = fontes || [];
  const setItem = (i, patch) => onChange(list.map((f, idx) => idx === i ? { ...f, ...patch } : f));
  const add = () => onChange([...list, { titulo: '', url: '' }]);
  const remove = (i) => onChange(list.filter((_, idx) => idx !== i));
  return (
    <div>
      {list.map((f, i) => (
        <div key={i} style={{ display: 'flex', gap: 6, marginBottom: 6 }}>
          <input style={{ ...inputStyle, flex: 1 }} placeholder="Título" value={f.titulo || ''} onChange={(e) => setItem(i, { titulo: e.target.value })} />
          <input style={{ ...inputStyle, flex: 1.4 }} placeholder="https://…" value={f.url || ''} onChange={(e) => setItem(i, { url: e.target.value })} />
          <button className="btn ghost sm" onClick={() => remove(i)} title="Remover" style={{ flexShrink: 0 }}><Icon name="trash" size={14} /></button>
        </div>
      ))}
      <button className="btn ghost sm" onClick={add}><Icon name="plus" size={13} /> Adicionar fonte</button>
    </div>
  );
};

// ============================================================
// Editor de corpo HTML com preview
// ============================================================
const HtmlEditor = ({ value, onChange, rows = 10 }) => {
  const [preview, setPreview] = React.useState(false);
  return (
    <div>
      <div style={{ display: 'flex', gap: 8, marginBottom: 6 }}>
        <button className={`btn sm ${preview ? 'ghost' : ''}`} onClick={() => setPreview(false)}>HTML</button>
        <button className={`btn sm ${preview ? '' : 'ghost'}`} onClick={() => setPreview(true)}>Pré-visualizar</button>
      </div>
      {preview ? (
        <div className="artigo-html" style={{ border: '1.5px solid var(--border)', borderRadius: 8, padding: '12px 14px', minHeight: rows * 20, maxHeight: 340, overflowY: 'auto', fontSize: 13.5, lineHeight: 1.6 }}
          dangerouslySetInnerHTML={{ __html: sanitizeArtigoHtml(value) }} />
      ) : (
        <textarea style={{ ...inputStyle, fontFamily: 'monospace', fontSize: 12.5, lineHeight: 1.5, resize: 'vertical' }} rows={rows}
          value={value || ''} onChange={(e) => onChange(e.target.value)} placeholder="<p>Corpo do artigo em HTML…</p>" />
      )}
    </div>
  );
};

// ============================================================
// Card de artigo
// ============================================================
const ArtigoCard = ({ artigo, onAprovar, onDevolver, onRejeitar, onEditar, onLer, onPublicarAgora, isPartner }) => {
  const pendente = artigo.status === 'pendente_aprovacao';
  const publicavelAgora = (artigo.status === 'agendado' || artigo.status === 'erro_publicacao');
  const fontes = Array.isArray(artigo.fontes) ? artigo.fontes : [];
  return (
    <div className="card" style={{ padding: 18, marginBottom: 14, display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, flexWrap: 'wrap' }}>
        <div style={{ flex: 1, minWidth: 200 }}>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap', marginBottom: 6 }}>
            <AreaBadge area={artigo.area} />
            <StatusBadge status={artigo.status} />
            {!artigo.responsavel_id && <span style={{ fontSize: 10.5, fontWeight: 700, color: '#C2253E' }}>SEM RESPONSÁVEL</span>}
          </div>
          <h3
            onClick={() => onLer(artigo)}
            title="Ler artigo completo"
            style={{ margin: 0, fontSize: 16, fontWeight: 700, color: 'var(--pac-navy)', lineHeight: 1.3, cursor: 'pointer' }}
          >
            {artigo.titulo}
          </h3>
        </div>
        <div style={{ textAlign: 'right', fontSize: 11.5, color: 'var(--fg-muted)' }}>
          <div>Recebido {fmtDate(artigo.created_at)}</div>
          <div>Origem: {origemLabel(artigo.origem)}</div>
          {artigo.responsavel?.name && <div>Resp.: {artigo.responsavel.name}</div>}
        </div>
      </div>

      {/* Preview do corpo */}
      <div style={{ fontSize: 13, color: '#333', lineHeight: 1.55 }}>{artigoPlainText(artigo.corpo_html, 260)}</div>

      <div>
        <button className="btn ghost sm" onClick={() => onLer(artigo)}>
          <Icon name="eye" size={13} /> Ler artigo completo
        </button>
      </div>

      {/* Chamada para redes */}
      {artigo.chamada_redes && (
        <div style={{ background: 'var(--pac-neon-soft, #f7fae0)', border: '1px solid #e4ecb0', borderRadius: 8, padding: '10px 12px', fontSize: 12.5, color: '#4a5320' }}>
          <div style={{ fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.05em', marginBottom: 4, color: '#7a8330' }}>Chamada para redes</div>
          {artigo.chamada_redes}
        </div>
      )}

      {/* Fontes */}
      {fontes.length > 0 && (
        <div style={{ fontSize: 12 }}>
          <span style={{ color: 'var(--fg-muted)', fontWeight: 600 }}>Fontes: </span>
          {fontes.map((f, i) => (
            <span key={i}>
              {i > 0 && ' · '}
              {f.url ? <a href={f.url} target="_blank" rel="noopener noreferrer" style={{ color: 'var(--pac-navy)' }}>{f.titulo || f.url}</a> : (f.titulo || '')}
            </span>
          ))}
        </div>
      )}

      {/* Metadados por status */}
      {artigo.status === 'agendado' && (
        <div style={{ fontSize: 12.5, color: '#1e5f9e' }}><Icon name="clock" size={13} /> Publicação agendada para <b>{fmtDateTime(artigo.publish_at)}</b></div>
      )}
      {artigo.status === 'publicado' && (
        <div style={{ fontSize: 12.5, color: '#2f855a' }}><Icon name="check" size={13} /> Publicado em {fmtDateTime(artigo.published_at)}{artigo.site_slug ? ` · /${artigo.site_slug}` : ''}</div>
      )}
      {artigo.status === 'erro_publicacao' && artigo.error_message && (
        <div style={{ fontSize: 12.5, color: '#C2253E' }}><Icon name="alertTriangle" size={13} /> {artigo.error_message}</div>
      )}
      {artigo.status === 'em_revisao' && (
        <div style={{ fontSize: 12.5, color: '#805ad5' }}><Icon name="refresh" size={13} /> Devolvido ao Manus para revisão</div>
      )}
      {pendente && artigo.sugestao_publish_at && (
        <div style={{ fontSize: 12, color: 'var(--fg-muted)' }}><Icon name="calendar" size={12} /> Sugestão de publicação: <b>{fmtDateTime(artigo.sugestao_publish_at)}</b></div>
      )}

      {/* Ações */}
      {pendente && (
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', borderTop: '1px solid var(--border)', paddingTop: 12 }}>
          <button className="btn" onClick={() => onAprovar(artigo)}><Icon name="check" size={14} /> Aprovar</button>
          <button className="btn ghost" onClick={() => onEditar(artigo)}><Icon name="pen" size={14} /> Editar</button>
          <button className="btn ghost" onClick={() => onDevolver(artigo)}><Icon name="refresh" size={14} /> Devolver</button>
          <button className="btn ghost" onClick={() => onRejeitar(artigo)} style={{ color: '#C2253E' }}><Icon name="x" size={14} /> Rejeitar</button>
        </div>
      )}
      {publicavelAgora && isPartner && (
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', borderTop: '1px solid var(--border)', paddingTop: 12 }}>
          <button className="btn" onClick={() => onPublicarAgora(artigo)}><Icon name="zap" size={14} /> Publicar agora</button>
        </div>
      )}
    </div>
  );
};

// ── Modal: ler artigo completo (somente leitura) ─────────────────────────────
const LerArtigoModal = ({ artigo, onClose }) => {
  const fontes = Array.isArray(artigo.fontes) ? artigo.fontes : [];
  return (
    <ArtigoModal title="Artigo completo" onClose={onClose} width={720}>
      <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap', marginBottom: 10 }}>
        <AreaBadge area={artigo.area} />
        <StatusBadge status={artigo.status} />
      </div>
      <h2 style={{ margin: '0 0 4px', fontSize: 20, fontWeight: 800, color: 'var(--pac-navy)', fontFamily: 'Georgia, serif', lineHeight: 1.3 }}>
        {artigo.titulo}
      </h2>
      <div style={{ fontSize: 11.5, color: 'var(--fg-muted)', marginBottom: 18 }}>
        Recebido {fmtDate(artigo.created_at)} · Origem: <span>{origemLabel(artigo.origem)}</span>
        {artigo.responsavel?.name ? <> · Resp.: {artigo.responsavel.name}</> : null}
      </div>

      <div className="artigo-html" style={{ fontSize: 14, lineHeight: 1.7, color: '#222' }}
        dangerouslySetInnerHTML={{ __html: sanitizeArtigoHtml(artigo.corpo_html) }} />

      {artigo.chamada_redes && (
        <div style={{ background: 'var(--pac-neon-soft, #f7fae0)', border: '1px solid #e4ecb0', borderRadius: 8, padding: '10px 12px', fontSize: 12.5, color: '#4a5320', marginTop: 18 }}>
          <div style={{ fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.05em', marginBottom: 4, color: '#7a8330' }}>Chamada para redes</div>
          {artigo.chamada_redes}
        </div>
      )}

      {fontes.length > 0 && (
        <div style={{ fontSize: 12, marginTop: 14 }}>
          <div style={{ color: 'var(--fg-muted)', fontWeight: 600, marginBottom: 4 }}>Fontes</div>
          {fontes.map((f, i) => (
            <div key={i}>
              {f.url ? <a href={f.url} target="_blank" rel="noopener noreferrer" style={{ color: 'var(--pac-navy)' }}>{f.titulo || f.url}</a> : (f.titulo || '')}
            </div>
          ))}
        </div>
      )}

      <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 20 }}>
        <button className="btn ghost" onClick={onClose}>Fechar</button>
      </div>
    </ArtigoModal>
  );
};

// ============================================================
// Aba "Para Aprovar"
// ============================================================
const ParaAprovar = ({ currentUser }) => {
  const [artigos, setArtigos] = React.useState(null);
  const [statusF, setStatusF] = React.useState('pendente_aprovacao');
  const [areaF, setAreaF] = React.useState('');
  const [modal, setModal] = React.useState(null); // { type, artigo }
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');

  // "Publicar agora" (fora do agendamento) é restrito a sócios — mesma trava
  // já aplicada pelo backend em POST /api/artigos/:id/publicar-agora.
  const isPartner = currentUser?.role === 'socio_admin' || currentUser?.role === 'socio';

  // Fila compartilhada: todos veem todos os artigos diretamente, sem filtro
  // de "meus"/"sem responsável" — cada um sabe sua área e aprova o que for seu.
  const load = React.useCallback(() => {
    setArtigos(null);
    const filters = {};
    if (statusF) filters.status = statusF;
    if (areaF) filters.area = areaF;
    window.PACApi.artigos.list(filters)
      .then(setArtigos)
      .catch((e) => { setErr(e.message || 'Erro ao carregar.'); setArtigos([]); });
  }, [statusF, areaF]);

  React.useEffect(load, [load]);

  const act = async (fn) => {
    setBusy(true); setErr('');
    try { await fn(); setModal(null); load(); }
    catch (e) { setErr(e.message || 'Erro.'); }
    finally { setBusy(false); }
  };

  return (
    <div>
      {/* Filtros */}
      <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginBottom: 16, alignItems: 'center' }}>
        <select value={statusF} onChange={(e) => setStatusF(e.target.value)} style={{ ...inputStyle, width: 'auto' }}>
          <option value="pendente_aprovacao">Pendentes</option>
          <option value="agendado">Agendados</option>
          <option value="publicado">Publicados</option>
          <option value="em_revisao">Em revisão</option>
          <option value="erro_publicacao">Com erro</option>
          <option value="rejeitado">Rejeitados</option>
          <option value="">Todos os status</option>
        </select>
        <select value={areaF} onChange={(e) => setAreaF(e.target.value)} style={{ ...inputStyle, width: 'auto' }}>
          <option value="">Todas as áreas</option>
          {ARTIGO_AREAS.map(a => <option key={a.slug} value={a.slug}>{a.label}</option>)}
        </select>
        <button className="btn ghost sm" onClick={load} title="Atualizar"><Icon name="refresh" size={14} /></button>
      </div>

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

      {artigos === null ? (
        <div style={{ padding: 40, textAlign: 'center', color: 'var(--fg-muted)' }}><span className="spinner" /> Carregando…</div>
      ) : artigos.length === 0 ? (
        <div style={{ padding: 48, textAlign: 'center', color: 'var(--fg-muted)', fontSize: 13.5 }}>
          Nenhum artigo aqui.<br />
          <span style={{ fontSize: 12 }}>Artigos enviados pelo Manus aparecem nesta lista para aprovação.</span>
        </div>
      ) : (
        artigos.map(a => (
          <ArtigoCard key={a.id} artigo={a} isPartner={isPartner}
            onAprovar={(art) => setModal({ type: 'aprovar', artigo: art })}
            onDevolver={(art) => setModal({ type: 'devolver', artigo: art })}
            onRejeitar={(art) => setModal({ type: 'rejeitar', artigo: art })}
            onEditar={(art) => setModal({ type: 'editar', artigo: art })}
            onLer={(art) => setModal({ type: 'ler', artigo: art })}
            onPublicarAgora={(art) => setModal({ type: 'publicar', artigo: art })}
          />
        ))
      )}

      {modal?.type === 'aprovar' && (
        <AprovarModal artigo={modal.artigo} busy={busy} err={err}
          onClose={() => setModal(null)}
          onConfirm={(publishAt) => act(() => window.PACApi.artigos.aprovar(modal.artigo.id, publishAt))} />
      )}
      {modal?.type === 'devolver' && (
        <DevolverModal artigo={modal.artigo} busy={busy} err={err}
          onClose={() => setModal(null)}
          onConfirm={(obs) => act(() => window.PACApi.artigos.devolver(modal.artigo.id, obs))} />
      )}
      {modal?.type === 'rejeitar' && (
        <ArtigoModal title="Rejeitar artigo" onClose={() => setModal(null)} width={420}>
          <p style={{ fontSize: 13.5, color: '#333', marginTop: 0 }}>Rejeitar <b>{modal.artigo.titulo}</b>? Ele não será publicado no site.</p>
          {err && <div style={{ color: '#C2253E', fontSize: 12.5, marginBottom: 10 }}>{err}</div>}
          <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
            <button className="btn ghost" onClick={() => setModal(null)}>Cancelar</button>
            <button className="btn" disabled={busy} style={{ background: '#C2253E' }} onClick={() => act(() => window.PACApi.artigos.rejeitar(modal.artigo.id))}>{busy ? 'Rejeitando…' : 'Rejeitar'}</button>
          </div>
        </ArtigoModal>
      )}
      {modal?.type === 'editar' && (
        <EditarModal artigo={modal.artigo} busy={busy} err={err}
          onClose={() => setModal(null)}
          onSave={(fields) => act(() => window.PACApi.artigos.update(modal.artigo.id, fields))} />
      )}
      {modal?.type === 'ler' && (
        <LerArtigoModal artigo={modal.artigo} onClose={() => setModal(null)} />
      )}
      {modal?.type === 'publicar' && (
        <ArtigoModal title="Publicar agora" onClose={() => setModal(null)} width={440}>
          <p style={{ fontSize: 13.5, color: '#333', marginTop: 0 }}>
            Publicar <b>{modal.artigo.titulo}</b> agora mesmo no site, sem esperar o agendamento
            {modal.artigo.publish_at ? <> (previsto para <b>{fmtDateTime(modal.artigo.publish_at)}</b>)</> : null}?
          </p>
          <p style={{ fontSize: 12, color: 'var(--fg-muted)' }}>Isso publica de verdade no site institucional — não dá para desfazer pelo PAC Sistema.</p>
          {err && <div style={{ color: '#C2253E', fontSize: 12.5, marginBottom: 10 }}>{err}</div>}
          <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
            <button className="btn ghost" onClick={() => setModal(null)}>Cancelar</button>
            <button className="btn" disabled={busy} onClick={() => act(() => window.PACApi.artigos.publicarAgora(modal.artigo.id))}>
              {busy ? 'Publicando…' : <><Icon name="zap" size={14} /> Publicar agora</>}
            </button>
          </div>
        </ArtigoModal>
      )}
    </div>
  );
};

// ── Modal: aprovar (confirma/ajusta data) ────────────────────────────────────
const AprovarModal = ({ artigo, onClose, onConfirm, busy, err }) => {
  const [dt, setDt] = React.useState(toLocalInput(artigo.sugestao_publish_at || artigo.publish_at));
  const confirmar = () => {
    // datetime-local (hora local) → ISO com offset do navegador
    const iso = new Date(dt).toISOString();
    onConfirm(iso);
  };
  return (
    <ArtigoModal title="Aprovar e agendar publicação" onClose={onClose} width={460}>
      <p style={{ fontSize: 13, color: '#333', marginTop: 0 }}><b>{artigo.titulo}</b></p>
      <label style={labelStyle}>Data e hora de publicação</label>
      <input type="datetime-local" style={inputStyle} value={dt} onChange={(e) => setDt(e.target.value)} />
      <p style={{ fontSize: 11.5, color: 'var(--fg-muted)', margin: '8px 0 0' }}>Sugestão automática: {fmtDateTime(artigo.sugestao_publish_at)}. Você pode ajustar.</p>
      {err && <div style={{ color: '#C2253E', fontSize: 12.5, marginTop: 10 }}>{err}</div>}
      <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 18 }}>
        <button className="btn ghost" onClick={onClose}>Cancelar</button>
        <button className="btn" disabled={busy || !dt} onClick={confirmar}>{busy ? 'Agendando…' : 'Aprovar e agendar'}</button>
      </div>
    </ArtigoModal>
  );
};

// ── Modal: devolver para revisão ─────────────────────────────────────────────
const DevolverModal = ({ artigo, onClose, onConfirm, busy, err }) => {
  const [obs, setObs] = React.useState('');
  return (
    <ArtigoModal title="Devolver para revisão" onClose={onClose} width={480}>
      <p style={{ fontSize: 13, color: '#333', marginTop: 0 }}>O artigo <b>{artigo.titulo}</b> volta ao Manus com suas observações.</p>
      <label style={labelStyle}>Observações (obrigatório)</label>
      <textarea style={{ ...inputStyle, resize: 'vertical' }} rows={4} value={obs} onChange={(e) => setObs(e.target.value)} placeholder="O que precisa ser ajustado…" />
      {err && <div style={{ color: '#C2253E', fontSize: 12.5, marginTop: 10 }}>{err}</div>}
      <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 18 }}>
        <button className="btn ghost" onClick={onClose}>Cancelar</button>
        <button className="btn" disabled={busy || !obs.trim()} onClick={() => onConfirm(obs.trim())}>{busy ? 'Enviando…' : 'Devolver ao Manus'}</button>
      </div>
    </ArtigoModal>
  );
};

// ── Modal: editar ────────────────────────────────────────────────────────────
const EditarModal = ({ artigo, onClose, onSave, busy, err }) => {
  const [titulo, setTitulo] = React.useState(artigo.titulo || '');
  const [area, setArea] = React.useState(artigo.area || '');
  const [corpo, setCorpo] = React.useState(artigo.corpo_html || '');
  const [chamada, setChamada] = React.useState(artigo.chamada_redes || '');
  const [fontes, setFontes] = React.useState(Array.isArray(artigo.fontes) ? artigo.fontes : []);
  const salvar = () => onSave({ titulo, area, corpo_html: corpo, chamada_redes: chamada, fontes: fontes.filter(f => f.titulo || f.url) });
  return (
    <ArtigoModal title="Editar artigo" onClose={onClose} width={640}>
      <label style={labelStyle}>Título</label>
      <input style={inputStyle} value={titulo} onChange={(e) => setTitulo(e.target.value)} />
      <label style={{ ...labelStyle, marginTop: 14 }}>Área</label>
      <select style={inputStyle} value={area} onChange={(e) => setArea(e.target.value)}>
        {ARTIGO_AREAS.map(a => <option key={a.slug} value={a.slug}>{a.label}</option>)}
      </select>
      <label style={{ ...labelStyle, marginTop: 14 }}>Corpo (HTML)</label>
      <HtmlEditor value={corpo} onChange={setCorpo} />
      <label style={{ ...labelStyle, marginTop: 14 }}>Chamada para redes</label>
      <textarea style={{ ...inputStyle, resize: 'vertical' }} rows={2} value={chamada} onChange={(e) => setChamada(e.target.value)} />
      <label style={{ ...labelStyle, marginTop: 14 }}>Fontes</label>
      <FontesEditor fontes={fontes} onChange={setFontes} />
      {err && <div style={{ color: '#C2253E', fontSize: 12.5, marginTop: 10 }}>{err}</div>}
      <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 18 }}>
        <button className="btn ghost" onClick={onClose}>Cancelar</button>
        <button className="btn" disabled={busy || !titulo.trim() || !corpo.trim()} onClick={salvar}>{busy ? 'Salvando…' : 'Salvar alterações'}</button>
      </div>
    </ArtigoModal>
  );
};

// ============================================================
// Aba "Enviar para o Manus"
// ============================================================
const EnviarManus = () => {
  const [modo, setModo] = React.useState('briefing');
  const [area, setArea] = React.useState('contratual');
  // briefing
  const [topico, setTopico] = React.useState('');
  const [obs, setObs] = React.useState('');
  const [fontes, setFontes] = React.useState([]);
  // pronto
  const [titulo, setTitulo] = React.useState('');
  const [corpo, setCorpo] = React.useState('');
  const [chamada, setChamada] = React.useState('');
  const [publishAt, setPublishAt] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [msg, setMsg] = React.useState('');
  const [err, setErr] = React.useState('');

  const submit = async () => {
    setBusy(true); setErr(''); setMsg('');
    try {
      const payload = modo === 'briefing'
        ? { modo, area, topico, observacoes: obs, fontes: fontes.filter(f => f.titulo || f.url) }
        : { modo, area, titulo, corpo_html: corpo, chamada_redes: chamada, ...(publishAt ? { publish_at: new Date(publishAt).toISOString() } : {}) };
      await window.PACApi.artigos.enviarManual(payload);
      setMsg('Enviado ao Manus com sucesso.');
      setTopico(''); setObs(''); setFontes([]); setTitulo(''); setCorpo(''); setChamada(''); setPublishAt('');
    } catch (e) { setErr(e.message || 'Erro ao enviar.'); }
    finally { setBusy(false); }
  };

  const podeEnviar = modo === 'briefing' ? !!topico.trim() : (!!titulo.trim() && !!corpo.trim());

  return (
    <div style={{ maxWidth: 720 }}>
      <div style={{ display: 'flex', gap: 8, marginBottom: 18 }}>
        <button className={`btn ${modo === 'briefing' ? '' : 'ghost'}`} onClick={() => setModo('briefing')}>Briefing (Manus escreve)</button>
        <button className={`btn ${modo === 'pronto' ? '' : 'ghost'}`} onClick={() => setModo('pronto')}>Artigo pronto (só publicar)</button>
      </div>

      <div className="card" style={{ padding: 20 }}>
        <label style={labelStyle}>Área</label>
        <select style={inputStyle} value={area} onChange={(e) => setArea(e.target.value)}>
          {ARTIGO_AREAS.map(a => <option key={a.slug} value={a.slug}>{a.label}</option>)}
        </select>

        {modo === 'briefing' ? (
          <>
            <label style={{ ...labelStyle, marginTop: 14 }}>Tópico / ideia central</label>
            <textarea style={{ ...inputStyle, resize: 'vertical' }} rows={4} value={topico} onChange={(e) => setTopico(e.target.value)} placeholder="Sobre o que o artigo deve tratar…" />
            <label style={{ ...labelStyle, marginTop: 14 }}>Fontes / referências</label>
            <FontesEditor fontes={fontes} onChange={setFontes} />
            <label style={{ ...labelStyle, marginTop: 14 }}>Observações de tom / abordagem (opcional)</label>
            <textarea style={{ ...inputStyle, resize: 'vertical' }} rows={2} value={obs} onChange={(e) => setObs(e.target.value)} />
          </>
        ) : (
          <>
            <label style={{ ...labelStyle, marginTop: 14 }}>Título</label>
            <input style={inputStyle} value={titulo} onChange={(e) => setTitulo(e.target.value)} />
            <label style={{ ...labelStyle, marginTop: 14 }}>Corpo (HTML)</label>
            <HtmlEditor value={corpo} onChange={setCorpo} />
            <label style={{ ...labelStyle, marginTop: 14 }}>Chamada para redes</label>
            <textarea style={{ ...inputStyle, resize: 'vertical' }} rows={2} value={chamada} onChange={(e) => setChamada(e.target.value)} />
            <label style={{ ...labelStyle, marginTop: 14 }}>Data de publicação desejada (opcional)</label>
            <input type="datetime-local" style={inputStyle} value={publishAt} onChange={(e) => setPublishAt(e.target.value)} />
          </>
        )}

        {err && <div style={{ color: '#C2253E', fontSize: 12.5, marginTop: 14 }}>{err}</div>}
        {msg && <div style={{ color: '#2f855a', fontSize: 12.5, marginTop: 14 }}>{msg}</div>}
        <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 18 }}>
          <button className="btn" disabled={busy || !podeEnviar} onClick={submit}>{busy ? 'Enviando…' : <><Icon name="send" size={14} /> Enviar ao Manus</>}</button>
        </div>
      </div>
      <p style={{ fontSize: 11.5, color: 'var(--fg-muted)', marginTop: 12 }}>
        O Manus recebe o pedido, gera/padroniza o artigo e o devolve ao PAC Sistema, onde aparece na aba <b>Para Aprovar</b>.
      </p>
    </div>
  );
};

// ============================================================
// Componente principal
// ============================================================
const Artigos = ({ currentUser }) => {
  const [tab, setTab] = React.useState('aprovar');
  return (
    <div className="view-wrap" style={{ padding: '24px 28px', maxWidth: 1080, margin: '0 auto' }}>
      <div style={{ marginBottom: 20 }}>
        <h1 style={{ margin: 0, fontSize: 24, fontWeight: 800, color: 'var(--pac-navy)', fontFamily: 'Georgia, serif' }}>Artigos</h1>
        <p style={{ margin: '4px 0 0', fontSize: 13, color: 'var(--fg-muted)' }}>Recepção, aprovação e publicação automática no site institucional.</p>
      </div>

      <div style={{ display: 'flex', gap: 4, borderBottom: '1px solid var(--border)', marginBottom: 20 }}>
        {[['aprovar', 'Para Aprovar'], ['enviar', 'Enviar para o Manus']].map(([k, lbl]) => (
          <button key={k} onClick={() => setTab(k)}
            style={{ background: 'none', border: 'none', padding: '10px 16px', fontSize: 13.5, fontWeight: 700, cursor: 'pointer',
              color: tab === k ? 'var(--pac-navy)' : 'var(--fg-muted)',
              borderBottom: tab === k ? '2px solid var(--pac-navy)' : '2px solid transparent', marginBottom: -1 }}>
            {lbl}
          </button>
        ))}
      </div>

      {tab === 'aprovar' ? <ParaAprovar currentUser={currentUser} /> : <EnviarManus />}
    </div>
  );
};

Object.assign(window, { Artigos });
