/* screen_marketing_conteudos.jsx
   Marketing · Produção de Conteúdo — canvas de nodes por campanha.
   Fluxo: Briefing → Conceito → Imagem/Vídeo → Composição → Formato → Publicação.
   Canvas implementado em React puro + SVG (sem ReactFlow).
   Dados: window.MktCampanhasAPI (mock local, real quando API disponível).

   Expõe window.MktConteudosScreen.
*/

// ── Layout constants ─────────────────────────────────────────────────────────
const _NODE_W   = 260;
const _COL_GAP  = 72;
const _COL_STEP = _NODE_W + _COL_GAP;
const _ROW_STEP = 280;  // vertical slot per row
const _COL = {
  briefing:   0,
  conceito:   _COL_STEP,
  criativo:   _COL_STEP * 2,
  composicao: _COL_STEP * 3,
  formato:    _COL_STEP * 4,
  publicacao: _COL_STEP * 5,
};

// ── Status helpers ───────────────────────────────────────────────────────────
const _SC = {
  aprovado:'#22c55e', approved:'#22c55e', pronto:'#22c55e',
  publicado:'#3859D0', em_conteudo:'#3859D0',
  pendente:'#f59e0b', copy_pendente:'#f59e0b', agendado:'#f59e0b',
  rejeitado:'#ef4444', erro:'#ef4444',
  revisao:'#e879f9', generating:'#e879f9',
  vazio:'#475569', conceito:'#94a3b8', draft:'#94a3b8',
};
const _SL = {
  aprovado:'Aprovado', approved:'Aprovado', pronto:'Pronto',
  publicado:'Publicado', em_conteudo:'Em produção',
  pendente:'Pendente', copy_pendente:'Copy pendente', agendado:'Agendado',
  rejeitado:'Rejeitado', erro:'Erro',
  revisao:'Revisão', generating:'A gerar',
  vazio:'Por fazer', conceito:'Em curso', draft:'Rascunho',
};
const _sc = s => _SC[s] || '#475569';
const _sl = s => _SL[s] || s || '—';

// ── NodeShell ────────────────────────────────────────────────────────────────
const NodeShell = ({ icon, label, status, children, footer }) => {
  const col = _sc(status);
  return (
    <div style={{
      width: _NODE_W, background: '#1e293b',
      border: `2px solid ${col}`, borderRadius: 10, overflow: 'hidden',
      fontFamily: 'var(--font-text, Inter, system-ui, sans-serif)',
      boxShadow: `0 0 0 1px ${col}22, 0 4px 20px #0009`,
    }}>
      <div style={{
        padding: '8px 12px', borderBottom: '1px solid #334155',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        background: '#162032',
      }}>
        <span style={{ color: '#94a3b8', fontSize: 11, display: 'flex', alignItems: 'center', gap: 6 }}>
          {icon} {label}
        </span>
        {status && (
          <span style={{
            background: `${col}22`, color: col, borderRadius: 4,
            padding: '2px 7px', fontSize: 10, fontWeight: 600, letterSpacing: '0.04em',
          }}>{_sl(status)}</span>
        )}
      </div>
      {children && <div style={{ padding: '10px 12px', minHeight: 60 }}>{children}</div>}
      {footer && (
        <div style={{ padding: '8px 10px', borderTop: '1px solid #1e3a5f', display: 'flex', gap: 6 }}>
          {footer}
        </div>
      )}
    </div>
  );
};

const NField = ({ label, value }) => {
  if (!value) return null;
  return (
    <div style={{ marginBottom: 6 }}>
      <div style={{ fontSize: 9, color: '#64748b', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 2 }}>{label}</div>
      <div style={{ fontSize: 11.5, color: '#cbd5e1', lineHeight: 1.5, maxHeight: 60, overflow: 'hidden' }}>{value}</div>
    </div>
  );
};

const NBtn = ({ children, onClick, variant = 'secondary', disabled }) => {
  const bg = variant === 'primary' ? '#3859D0' : '#334155';
  return (
    <button onClick={onClick} disabled={disabled} style={{
      flex: 1, background: bg, border: 'none', borderRadius: 6,
      color: '#cbd5e1', padding: '5px 0', cursor: disabled ? 'not-allowed' : 'pointer',
      fontSize: 11, fontWeight: 500, opacity: disabled ? 0.55 : 1, fontFamily: 'inherit',
    }}>{children}</button>
  );
};

// ── Node types ───────────────────────────────────────────────────────────────
const BriefingNode = ({ data, onAction }) => {
  const c = data.conteudo || {};
  return (
    <NodeShell icon="📋" label="Briefing" status={data.status}>
      <NField label="Marca"    value={c.brand} />
      <NField label="Produto"  value={c.product} />
      <NField label="Canal"    value={c.canal} />
      <NField label="Período"  value={c.periodo} />
    </NodeShell>
  );
};

const ConceitoNode = ({ data, onAction }) => {
  const c = data.conteudo || {};
  const empty = data.status === 'vazio';
  return (
    <NodeShell icon="✍️" label="Conceito + Copy" status={data.status}
      footer={
        empty
          ? <NBtn variant="primary" onClick={() => onAction('gerar', data)}>Gerar Conceito</NBtn>
          : data.status === 'pendente'
            ? <><NBtn variant="primary" onClick={() => onAction('aprovar_copy', data)}>Aprovar</NBtn><NBtn onClick={() => onAction('regenerar', data)}>Regenerar</NBtn></>
            : <NBtn onClick={() => onAction('regenerar', data)}>Regenerar</NBtn>
      }>
      {empty
        ? <p style={{ color: '#475569', fontSize: 11, textAlign: 'center', marginTop: 12 }}>Clica em Gerar Conceito para a Digi AI criar o copy.</p>
        : <>
            {c.conceito && <NField label="Conceito" value={c.conceito} />}
            <NField label="Headline" value={c.headline} />
            <NField label="CTA"      value={c.cta} />
          </>
      }
    </NodeShell>
  );
};

const ImagemNode = ({ data, onAction }) => (
  <NodeShell icon="🖼" label="Imagem" status={data.status}
    footer={
      data.status === 'vazio'
        ? <NBtn variant="primary" onClick={() => onAction('gerar_imagem', data)}>Gerar Imagem</NBtn>
        : <><NBtn onClick={() => onAction('regen_criativo', data)}>Regenerar</NBtn>
            {data.status !== 'aprovado' && <NBtn variant="primary" onClick={() => onAction('aprovar_criativo', data)}>Aprovar</NBtn>}</>
    }>
    {data.previewUrl
      ? <img src={data.previewUrl} alt="" style={{ width: '100%', height: 120, objectFit: 'cover', borderRadius: 6 }} />
      : <div style={{ height: 120, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#475569', fontSize: 11 }}>
          {data.status === 'vazio' ? 'Imagem não gerada' : 'A aguardar imagem…'}
        </div>
    }
  </NodeShell>
);

const VideoNode = ({ data, onAction }) => (
  <NodeShell icon="🎬" label="Vídeo" status={data.status}
    footer={
      data.status === 'vazio'
        ? <NBtn variant="primary" onClick={() => onAction('gerar_video', data)}>Gerar Vídeo</NBtn>
        : <><NBtn onClick={() => onAction('regen_criativo', data)}>Regenerar</NBtn>
            {data.status !== 'aprovado' && <NBtn variant="primary" onClick={() => onAction('aprovar_criativo', data)}>Aprovar</NBtn>}</>
    }>
    <div style={{ height: 120, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#475569', fontSize: 11 }}>
      {data.status === 'vazio' ? 'Vídeo não gerado' : data.status === 'aprovado' ? '✓ Pronto' : 'A gerar…'}
    </div>
  </NodeShell>
);

const ComposicaoNode = ({ data, onAction }) => (
  <NodeShell icon="🎨" label="Composição" status={data.status}
    footer={
      data.status === 'vazio'
        ? <NBtn variant="primary" onClick={() => onAction('compor', data)}>Compor Formatos</NBtn>
        : <NBtn onClick={() => onAction('ver_formatos', data)}>Ver Todos</NBtn>
    }>
    <p style={{ color: '#64748b', fontSize: 11, lineHeight: 1.6 }}>
      {data.status === 'vazio'
        ? 'Aplica logo + texto à imagem em todos os formatos.'
        : 'Formatos compostos com logo e copy.'}
    </p>
  </NodeShell>
);

const FormatoNode = ({ data }) => (
  <NodeShell icon="📐" label={data.label} status={data.previewUrl ? 'pronto' : 'vazio'}>
    {data.previewUrl
      ? <img src={data.previewUrl} alt="" style={{ width: '100%', height: 80, objectFit: 'cover', borderRadius: 6 }} />
      : <div style={{ height: 80, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#475569', fontSize: 11 }}>A compor…</div>
    }
  </NodeShell>
);

const CANAL_ICON = { instagram: '📸', facebook: '👍', youtube: '▶', linkedin: '💼', newsletter: '✉', 'muppi-led': '📺' };
const PublicacaoNode = ({ data, onAction }) => (
  <NodeShell icon={CANAL_ICON[data.canal] || '📢'} label={data.canal} status={data.status}
    footer={
      (data.status === 'vazio' || data.status === 'agendado')
        ? <NBtn variant="primary" onClick={() => onAction('agendar', data)}>
            {data.status === 'agendado' ? 'Reagendar' : 'Agendar'}
          </NBtn>
        : undefined
    }>
    <p style={{ color: '#64748b', fontSize: 11, lineHeight: 1.6 }}>
      {data.status === 'publicado' ? '✓ Publicado com sucesso.'
        : data.status === 'agendado' ? '🕐 Agendado para publicação.'
        : data.status === 'erro'    ? '⚠ Erro na publicação.'
        : 'Pronto para agendar.'}
    </p>
  </NodeShell>
);

// ── Build graph (replacing dagre with column-based layout) ───────────────────
function _buildGraph(campanha) {
  const nodes = [];
  const edges = [];
  let maxRows = 1;

  // Briefing
  const b = campanha.briefing || {};
  nodes.push({ id: 'briefing', type: 'briefing', x: _COL.briefing, y: 0, data: {
    status: b.status, conteudo: {
      brand: b.brand_name, product: b.product_name,
      canal: b.campanha?.canal, periodo: b.campanha?.periodo,
    },
  }});

  // Conceito
  const copy = campanha.copy;
  nodes.push({ id: 'conceito', type: 'conceito', x: _COL.conceito, y: 0, data: copy
    ? { status: copy.status, item_id: copy.id, campanha_id: campanha.id, conteudo: { conceito: copy.conceito, headline: copy.headline, cta: copy.cta } }
    : { status: 'vazio', campanha_id: campanha.id }
  });
  edges.push({ id: 'e-b-c', from: 'briefing', to: 'conceito' });

  // Criativos
  const criativos = campanha.criativos || [];
  if (criativos.length === 0) {
    nodes.push({ id: 'cri-ph', type: 'imagem', x: _COL.criativo, y: 0, data: { status: 'vazio', campanha_id: campanha.id } });
    edges.push({ id: 'e-c-cri', from: 'conceito', to: 'cri-ph' });
    nodes.push({ id: 'comp-ph', type: 'composicao', x: _COL.composicao, y: 0, data: { status: 'vazio' } });
    edges.push({ id: 'e-cri-comp', from: 'cri-ph', to: 'comp-ph' });
    nodes.push({ id: 'pub-ph', type: 'publicacao', x: _COL.publicacao, y: 0, data: { status: 'vazio', canal: 'instagram', campanha_id: campanha.id } });
  } else {
    criativos.forEach((cri, i) => {
      const y = i * _ROW_STEP;
      if (i > 0) maxRows = Math.max(maxRows, i + 1);
      const criId = `cri-${cri.id}`;
      nodes.push({ id: criId, type: cri.tipo === 'video' ? 'video' : 'imagem', x: _COL.criativo, y, data: {
        status: cri.status, item_id: cri.id, campanha_id: campanha.id, previewUrl: cri.url_base || null,
      }});
      edges.push({ id: `e-c-${criId}`, from: 'conceito', to: criId });

      const compId = `comp-${cri.id}`;
      const fmtEntries = Object.entries(cri.formatos || {});
      const hasFormatos = fmtEntries.length > 0;
      nodes.push({ id: compId, type: 'composicao', x: _COL.composicao, y, data: {
        status: hasFormatos ? 'pronto' : 'vazio', item_id: cri.id,
      }});
      edges.push({ id: `e-${criId}-comp`, from: criId, to: compId });

      fmtEntries.forEach(([fmt, url], j) => {
        const fmtId = `fmt-${cri.id}-${fmt}`;
        const fy = y + j * 180;
        nodes.push({ id: fmtId, type: 'formato', x: _COL.formato, y: fy, data: {
          label: fmt.replace(/_/g, ' '), previewUrl: url || null,
        }});
        edges.push({ id: `e-comp-${fmtId}`, from: compId, to: fmtId });
        maxRows = Math.max(maxRows, Math.ceil((fy + 180) / _ROW_STEP));
      });
    });

    const pubs = campanha.publicacoes || [];
    pubs.forEach((pub, i) => {
      const pubId = `pub-${pub.id}`;
      nodes.push({ id: pubId, type: 'publicacao', x: _COL.publicacao, y: i * 200, data: {
        status: pub.status, canal: pub.canal, item_id: pub.id,
      }});
      if (i === 0) {
        const lastCriId = criativos.length > 0 ? `cri-${criativos[criativos.length - 1].id}` : 'cri-ph';
        edges.push({ id: `e-${lastCriId}-${pubId}`, from: lastCriId, to: pubId });
      }
    });
    if (!pubs.length) {
      const pubPhId = 'pub-ph';
      const lastApproved = criativos.find(c => c.status === 'aprovado');
      nodes.push({ id: pubPhId, type: 'publicacao', x: _COL.publicacao, y: 0, data: {
        status: 'vazio', canal: 'instagram', campanha_id: campanha.id,
        criativo_id: lastApproved?.id || null,
      }});
    }
  }

  const canvasW = _COL.publicacao + _NODE_W + 40;
  const canvasH = Math.max(maxRows * _ROW_STEP, 320);

  // Vertical centering for single-node columns
  const yOffsets = {};
  ['briefing', 'conceito'].forEach(id => {
    const n = nodes.find(x => x.id === id);
    if (n) { n.y = Math.max(0, (canvasH / 2) - 110); }
  });

  return { nodes, edges, canvasW, canvasH };
}

// ── SVG Edges ────────────────────────────────────────────────────────────────
const _NODE_MID_Y = 110; // approx mid-height of a node

const CampanhaEdges = ({ edges, nodes }) => {
  const nodeById = {};
  nodes.forEach(n => { nodeById[n.id] = n; });

  const paths = edges.map(e => {
    const s = nodeById[e.from];
    const t = nodeById[e.to];
    if (!s || !t) return null;
    const sx = s.x + _NODE_W;
    const sy = s.y + _NODE_MID_Y;
    const tx = t.x;
    const ty = t.y + _NODE_MID_Y;
    const dx = (tx - sx) * 0.45;
    const d = `M${sx},${sy} C${sx + dx},${sy} ${tx - dx},${ty} ${tx},${ty}`;
    return <path key={e.id} d={d} stroke="#334155" strokeWidth="2" fill="none" strokeDasharray={ty !== sy ? '5,4' : undefined} />;
  });

  return (
    <svg style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', pointerEvents: 'none', overflow: 'visible' }}>
      <defs>
        <marker id="arr" markerWidth="6" markerHeight="6" refX="5" refY="3" orient="auto">
          <path d="M0,0 L6,3 L0,6 Z" fill="#475569" />
        </marker>
      </defs>
      {paths}
    </svg>
  );
};

// ── CampanhaCanvas ───────────────────────────────────────────────────────────
const CampanhaCanvas = ({ campanha, onAction }) => {
  const { nodes, edges, canvasW, canvasH } = _buildGraph(campanha);

  const renderNode = (n) => {
    const props = { data: n.data, onAction };
    const el = n.type === 'briefing'    ? <BriefingNode   {...props} />
             : n.type === 'conceito'    ? <ConceitoNode   {...props} />
             : n.type === 'imagem'      ? <ImagemNode     {...props} />
             : n.type === 'video'       ? <VideoNode      {...props} />
             : n.type === 'composicao'  ? <ComposicaoNode {...props} />
             : n.type === 'formato'     ? <FormatoNode    {...props} />
             : n.type === 'publicacao'  ? <PublicacaoNode {...props} />
             : null;
    return (
      <div key={n.id} style={{ position: 'absolute', left: n.x, top: n.y }}>{el}</div>
    );
  };

  // Stage labels
  const STAGE_LABELS = [
    { label: 'Briefing',    x: _COL.briefing },
    { label: 'Conceito',    x: _COL.conceito },
    { label: 'Criativo',    x: _COL.criativo },
    { label: 'Composição',  x: _COL.composicao },
    { label: 'Formato',     x: _COL.formato },
    { label: 'Publicação',  x: _COL.publicacao },
  ];

  return (
    <div style={{ background: '#0f172a', borderRadius: 12, overflow: 'auto', height: '100%', minHeight: 0 }}>
      {/* Stage header */}
      <div style={{
        display: 'flex', padding: '12px 20px 0', gap: 0,
        borderBottom: '1px solid #1e293b', background: '#0f172a',
        position: 'sticky', top: 0, zIndex: 2,
      }}>
        {STAGE_LABELS.map(sl => (
          <div key={sl.label} style={{
            width: _NODE_W, marginRight: _COL_GAP, flexShrink: 0,
            fontSize: 10, fontFamily: 'var(--font-mono, monospace)',
            color: '#475569', letterSpacing: '0.08em', paddingBottom: 10,
          }}>{sl.label.toUpperCase()}</div>
        ))}
      </div>

      {/* Canvas area */}
      <div style={{ position: 'relative', width: canvasW, minHeight: canvasH + 60, margin: '24px 20px 40px' }}>
        <CampanhaEdges edges={edges} nodes={nodes} />
        {nodes.map(renderNode)}
      </div>
    </div>
  );
};

// ── CampanhaCard (lista) ─────────────────────────────────────────────────────
const CAMP_STATUS_COLOR = {
  conceito: '#94a3b8', copy_pendente: '#f59e0b', copy_aprovado: '#3859D0',
  geracao: '#e879f9', aprovacao: '#f59e0b', publicado: '#22c55e',
};
const CAMP_STATUS_LABEL = {
  conceito: 'Conceito', copy_pendente: 'Copy pendente', copy_aprovado: 'Copy aprovado',
  geracao: 'A gerar', aprovacao: 'Em aprovação', publicado: 'Publicado',
};
const BRAND_COLOR_MAP = {
  mimaki: '#e60012', biond: '#00a86b', decal: '#f59e0b',
  alldecor: '#ec4899', sensek: '#8B2DE8', netscreen: '#F97316', digidelta: '#3859D0',
};

const CampanhaCard = ({ c, selected, onClick }) => {
  const col = CAMP_STATUS_COLOR[c.status] || '#94a3b8';
  const bCol = BRAND_COLOR_MAP[c.brand_slug] || '#3859D0';
  const [hover, setHover] = React.useState(false);
  return (
    <div onClick={onClick}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        padding: 16, borderRadius: 10, cursor: 'pointer',
        background: selected ? '#1e3a5f' : hover ? '#1e293b' : '#162032',
        border: `1px solid ${selected ? '#3859D0' : '#1e293b'}`,
        transition: 'background 120ms, border-color 120ms',
      }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
        <span style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em', color: bCol }}>
          {c.brand_name}
        </span>
        <span style={{
          fontSize: 10, fontWeight: 600, padding: '2px 8px', borderRadius: 99,
          background: `${col}22`, color: col,
        }}>{CAMP_STATUS_LABEL[c.status] || c.status}</span>
      </div>
      <div style={{ fontSize: 14, fontWeight: 600, color: '#f1f5f9', marginBottom: 4, lineHeight: 1.3 }}>{c.titulo}</div>
      <div style={{ fontSize: 11.5, color: '#64748b' }}>{c.product_name || '—'}</div>
      <div style={{ marginTop: 10, fontSize: 11, color: '#334155', fontFamily: 'var(--font-mono, monospace)' }}>
        {new Date(c.updated_at).toLocaleDateString('pt-PT', { day: '2-digit', month: 'short', year: 'numeric' })}
      </div>
    </div>
  );
};

// ── Toast ────────────────────────────────────────────────────────────────────
const _Toast = ({ msg, onClose }) => {
  React.useEffect(() => {
    if (!msg) return;
    const t = setTimeout(onClose, 3000);
    return () => clearTimeout(t);
  }, [msg]);
  if (!msg) return null;
  return (
    <div style={{
      position: 'fixed', bottom: 20, right: 20, zIndex: 9999,
      background: '#1e293b', color: '#cbd5e1', border: '1px solid #334155',
      padding: '10px 16px', borderRadius: 8, fontSize: 13,
      boxShadow: '0 8px 24px #0009', fontFamily: 'var(--font-sans, sans-serif)',
    }}>{msg}</div>
  );
};

// ── MktConteudosScreen (main) ────────────────────────────────────────────────
const MktConteudosScreen = () => {
  const [campanhas,  setCampanhas]  = React.useState(null);
  const [selected,   setSelected]   = React.useState(null);
  const [campDetail, setCampDetail] = React.useState(null);
  const [loading,    setLoading]    = React.useState(false);
  const [toast,      setToast]      = React.useState('');

  const loadDetail = React.useCallback(async (camp) => {
    if (!camp) { setCampDetail(null); return; }
    setLoading(true);
    const detail = await window.MktCampanhasAPI?.get(camp.id);
    setCampDetail(detail || camp);
    setLoading(false);
  }, []);

  React.useEffect(() => {
    (async () => {
      const pending = window.mktPendingConteudo;
      if (pending) window.mktPendingConteudo = null;

      const list = await window.MktCampanhasAPI?.list();
      const arr = Array.isArray(list) ? list : (window.MktCampanhasData || []);
      setCampanhas(arr);

      if (pending) {
        const match = arr.find(c => c.id === pending.id) || pending;
        setSelected(match);
        loadDetail(match);
      } else if (arr.length > 0) {
        setSelected(arr[0]);
        loadDetail(arr[0]);
      }
    })();
  }, [loadDetail]);

  const toast_ = (msg) => { setToast(msg); };

  const onAction = async (action, data) => {
    const api = window.MktCampanhasAPI;
    if (!api) { toast_('API não disponível em dev local'); return; }
    try {
      if (action === 'gerar')            { toast_('A gerar conceito via Digi AI…'); await api.gerar(data.campanha_id); await loadDetail(selected); }
      else if (action === 'aprovar_copy'){ toast_('Copy aprovado.'); await api.aprovarCopy(data.item_id); await loadDetail(selected); }
      else if (action === 'regenerar')   { toast_('A regenerar conceito…'); await api.gerar(data.campanha_id); await loadDetail(selected); }
      else if (action === 'gerar_imagem'){ toast_('A gerar imagem via FLUX…'); await api.gerarCriativo(data.campanha_id, 'imagem'); await loadDetail(selected); }
      else if (action === 'gerar_video') { toast_('A gerar vídeo…'); await api.gerarCriativo(data.campanha_id, 'video'); await loadDetail(selected); }
      else if (action === 'aprovar_criativo') { toast_('Criativo aprovado.'); await api.aprovarCriativo(data.item_id); await loadDetail(selected); }
      else if (action === 'agendar') {
        const criId = data.criativo_id || (campDetail?.criativos || []).find(c => c.status === 'aprovado')?.id;
        if (!criId) { toast_('Primeiro aprova um criativo antes de agendar.'); return; }
        toast_(`A agendar para ${data.canal}…`);
        await api.agendar(criId, data.canal);
        await loadDetail(selected);
      }
      else toast_(`Acção "${action}" em desenvolvimento.`);
    } catch (e) {
      toast_(`Erro: ${e.message}`);
    }
  };

  return (
    <div style={{
      display: 'flex', height: '100%', minHeight: 0,
      background: '#0f172a', color: '#e2e8f0',
      fontFamily: 'var(--font-text, Inter, system-ui, sans-serif)',
      overflow: 'hidden',
    }}>
      {/* Sidebar — lista de campanhas */}
      <div style={{
        width: 280, flexShrink: 0, borderRight: '1px solid #1e293b',
        display: 'flex', flexDirection: 'column', background: '#0f172a',
      }}>
        <div style={{ padding: '16px 16px 10px', borderBottom: '1px solid #1e293b' }}>
          <div style={{ fontSize: 10, color: '#475569', fontFamily: 'var(--font-mono, monospace)', letterSpacing: '0.08em', marginBottom: 6 }}>
            MARKETING · CONTEÚDO
          </div>
          <h2 style={{ margin: 0, fontSize: 17, fontWeight: 600, color: '#f1f5f9', letterSpacing: '-0.01em', fontFamily: 'var(--font-display, Montserrat, sans-serif)' }}>
            Produção
          </h2>
          <div style={{ marginTop: 4, fontSize: 12, color: '#475569' }}>
            {campanhas ? `${campanhas.length} campanha${campanhas.length !== 1 ? 's' : ''}` : '—'}
          </div>
        </div>

        <div className="scrollbar" style={{ flex: 1, overflowY: 'auto', padding: '10px 10px 24px', display: 'flex', flexDirection: 'column', gap: 6 }}>
          {campanhas === null && (
            [1,2,3].map(i => (
              <div key={i} style={{
                height: 88, borderRadius: 10,
                background: 'linear-gradient(90deg, #1e293b 25%, #243046 50%, #1e293b 75%)',
                backgroundSize: '200% 100%', animation: 'shimmer 1.4s ease-in-out infinite',
              }} />
            ))
          )}
          {campanhas?.map(c => (
            <CampanhaCard key={c.id} c={c} selected={selected?.id === c.id} onClick={() => {
              setSelected(c);
              loadDetail(c);
            }} />
          ))}
        </div>
      </div>

      {/* Canvas area */}
      <div style={{ flex: 1, minWidth: 0, minHeight: 0, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        {selected
          ? <>
              <div style={{
                padding: '10px 20px', borderBottom: '1px solid #1e293b', flexShrink: 0,
                display: 'flex', alignItems: 'center', gap: 12,
              }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 10, color: '#475569', fontFamily: 'var(--font-mono, monospace)', letterSpacing: '0.08em' }}>CAMPANHA</div>
                  <div style={{ fontSize: 16, fontWeight: 600, color: '#f1f5f9', marginTop: 2, fontFamily: 'var(--font-display, Montserrat, sans-serif)', letterSpacing: '-0.01em' }}>
                    {selected.titulo}
                  </div>
                </div>
                <span style={{
                  fontSize: 10.5, fontWeight: 600, padding: '4px 10px', borderRadius: 99,
                  background: `${CAMP_STATUS_COLOR[selected.status] || '#94a3b8'}22`,
                  color: CAMP_STATUS_COLOR[selected.status] || '#94a3b8',
                }}>{CAMP_STATUS_LABEL[selected.status] || selected.status}</span>
                {loading && <span style={{ fontSize: 11, color: '#475569' }}>A carregar…</span>}
              </div>
              <div style={{ flex: 1, minHeight: 0, padding: '16px 16px 0' }}>
                <CampanhaCanvas campanha={campDetail || selected} onAction={onAction} />
              </div>
            </>
          : (
            <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#334155', fontSize: 14 }}>
              Selecciona uma campanha
            </div>
          )
        }
      </div>

      <_Toast msg={toast} onClose={() => setToast('')} />
      <style>{`@keyframes shimmer{0%{background-position:200% 0}100%{background-position:-200% 0}}`}</style>
    </div>
  );
};

window.MktConteudosScreen = MktConteudosScreen;
// ─── (fim) ───────────────────────────────────────────────────────────────────
