const SeoViewConteudos = ({ marca, jobs }) => {
  const { data, err, load } = window.useSeoLoad('/api/marketing/seo/suggestions', [marca]);
  const [camps, setCamps] = React.useState([]);
  const [open, setOpen] = React.useState(null);
  const [campanha, setCampanha] = React.useState('');
  const [toast, setToast] = React.useState(null);
  const [busy, setBusy] = React.useState(false);
  const W = window;

  React.useEffect(() => {
    fetch('/api/marketing/campanhas', { credentials: 'same-origin' })
      .then(r => r.json()).then(d => setCamps(Array.isArray(d) ? d : (d.campanhas || d.rows || []))).catch(() => {});
  }, []);

  const send = () => {
    setBusy(true);
    window.seoFetch('/api/marketing/seo/suggestions/' + open.id + '/send-to-producao', {
      method: 'POST', body: JSON.stringify({ campanha_id: Number(campanha) }),
    }).then(r => { setOpen(null); setToast({ text: `Peça #${r.peca_id || ''} criada em Produção.` }); load(); })
      .catch(e => setToast({ text: 'Não foi enviado: ' + e.message, tone: 'bad' }))
      .finally(() => setBusy(false));
  };
  const reject = (id) => window.seoFetch('/api/marketing/seo/suggestions/' + id + '/reject', { method: 'POST', body: '{}' })
    .then(() => { setToast({ text: 'Sugestão rejeitada.' }); load(); })
    .catch(e => setToast({ text: 'Não foi rejeitada: ' + e.message, tone: 'bad' }));

  if (err) return <W.SeoError message={err} onRetry={load} />;
  if (!data) return <W.SeoLoading label="A carregar conteúdos…" />;
  const rows = data.suggestions || [];
  if (!rows.length) {
    return (
      <div style={{ display: 'grid', gap: 12 }}>
        <W.SeoMissingSources keys={['gsc', 'dataforseo']} jobs={jobs} title="Ainda não há sugestões de conteúdo." />
        <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>O agente sugere conteúdos quando uma pesquisa de produto está entre a posição 4 e 20, não tem página, ou a marca não é citada em assistentes AI.</div>
      </div>
    );
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      {rows.map(r => (
        <W.SeoCard key={r.id}>
          <div style={{ display: 'flex', gap: 10, fontSize: 12, alignItems: 'center', flexWrap: 'wrap' }}>
            <span style={{ fontSize: 11, fontWeight: 650, color: W.SEO_C.accent }}>{W.SEO_TRIGGER_LABELS[r.trigger] || r.trigger}</span>
            <span style={{ color: 'var(--text-muted)' }}>{r.tipo === 'website' ? 'Website' : 'Social'}</span>
            <span style={{ color: 'var(--text-dim)' }}>{r.domain}</span>
            <span style={{ marginLeft: 'auto', fontSize: 11, fontWeight: 650, color: r.status === 'sent' ? W.SEO_C.ok : 'var(--text-muted)' }}>{W.SEO_SUG_STATUS[r.status] || r.status}</span>
          </div>
          <div style={{ fontSize: 14, fontWeight: 650, marginTop: 6 }}>{r.title || (r.keywords || []).join(', ')}</div>
          <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 4 }}>{r.product_name || 'Sem produto'} · {(r.keywords || []).join(', ')}</div>
          {r.draft && <div style={{ fontSize: 12, marginTop: 8, whiteSpace: 'pre-wrap', color: 'var(--text)' }}>{String(r.draft).slice(0, 400)}</div>}
          <div style={{ display: 'flex', gap: 8, marginTop: 12, alignItems: 'center' }}>
            {r.status !== 'sent' && <W.SeoButton kind="primary" onClick={() => { setOpen(r); setCampanha(''); }}>Enviar para Produção</W.SeoButton>}
            {r.status !== 'sent' && <W.SeoButton onClick={() => reject(r.id)}>Rejeitar</W.SeoButton>}
            {r.producao_peca_id && <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-muted)' }}>Peça #{r.producao_peca_id}</span>}
          </div>
        </W.SeoCard>
      ))}
      {open && (
        <div role="dialog" aria-modal="true" aria-label="Escolher campanha" style={{ position: 'fixed', inset: 0, background: 'rgba(15,23,42,.35)', display: 'grid', placeItems: 'center', zIndex: 50 }} onClick={() => setOpen(null)}>
          <div style={{ padding: 18, width: 440, maxWidth: '92vw', background: 'var(--bg-elev)', borderRadius: 12, border: '1px solid var(--border)', boxShadow: '0 16px 40px rgba(15,23,42,.18)' }} onClick={e => e.stopPropagation()}>
            <W.SeoEyebrow>Enviar para Produção</W.SeoEyebrow>
            <div style={{ fontSize: 15, fontWeight: 650, margin: '6px 0 4px' }}>Escolher campanha</div>
            <div style={{ fontSize: 12, color: 'var(--text-muted)', marginBottom: 12 }}>{open.title}</div>
            <select aria-label="Campanha" value={campanha} onChange={e => setCampanha(e.target.value)} style={{ width: '100%', height: 34, padding: '0 10px', borderRadius: 8, border: '1px solid var(--border)', background: 'var(--bg)', color: 'var(--text)', fontSize: 13, marginBottom: 14 }}>
              <option value="">Campanha…</option>
              {camps.map(c => <option key={c.id} value={c.id}>{c.titulo || c.nome || c.name || ('#' + c.id)}</option>)}
            </select>
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
              <W.SeoButton onClick={() => setOpen(null)}>Cancelar</W.SeoButton>
              <W.SeoButton kind="primary" disabled={!campanha || busy} onClick={send}>{busy ? 'A criar…' : 'Criar peça'}</W.SeoButton>
            </div>
          </div>
        </div>
      )}
      <W.SeoToast msg={toast} onDone={() => setToast(null)} />
    </div>
  );
};
window.SeoViewConteudos = SeoViewConteudos;
