/* screen_marketing_plano_comunicacao.jsx
   Marketing · Plano de Comunicação — calendários editoriais trimestrais por marca.
   Expõe window.MktPlanoComunicacaoScreen.
*/

// ─── Constantes ───────────────────────────────────────────────────────────────

const PLANO_STATUS_CFG = {
  rascunho: { label: 'Rascunho',  color: 'var(--text-muted)', bg: 'var(--bg-sunken)' },
  gerado:   { label: 'Gerado',    color: '#3859D0',           bg: 'rgba(56,89,208,0.12)' },
  aprovado: { label: 'Aprovado',  color: '#22c55e',           bg: 'rgba(34,197,94,0.12)' },
  em_curso: { label: 'Em Curso',  color: '#f59e0b',           bg: 'rgba(245,158,11,0.12)' },
  fechado:  { label: 'Fechado',   color: 'var(--text-dim)',   bg: 'var(--bg-sunken)' },
};

const ITEM_STATUS_CFG = {
  planeado:    { label: 'Planeado',    color: '#64748b',  bg: 'rgba(100,116,139,0.15)' },
  em_briefing: { label: 'Em Briefing', color: '#f59e0b',  bg: 'rgba(245,158,11,0.15)' },
  em_campanha: { label: 'Em Campanha', color: '#3859D0',  bg: 'rgba(56,89,208,0.15)' },
  em_producao: { label: 'Em Produção', color: '#8b5cf6',  bg: 'rgba(139,92,246,0.15)' },
  aprovado:    { label: 'Aprovado',    color: '#22c55e',  bg: 'rgba(34,197,94,0.15)' },
  no_ar:       { label: 'No Ar',       color: '#16a34a',  bg: 'rgba(34,197,94,0.25)' },
  arquivado:   { label: 'Arquivado',   color: '#475569',  bg: 'rgba(100,116,139,0.1)' },
};

const PC_CANAL_LABELS = {
  email:'Email', linkedin:'LinkedIn', instagram:'Instagram', facebook:'Facebook',
  blog:'Blog', google_ads:'Google Ads', meta_ads:'Meta Ads', youtube:'YouTube',
  whatsapp:'WhatsApp', pr:'PR', eventos:'Eventos',
};

const CANAIS_OPTS = Object.keys(PC_CANAL_LABELS);
const ANOS = [2025, 2026, 2027];
const TRIMESTRES = [1, 2, 3, 4];
const SEMANAS = Array.from({ length: 13 }, (_, i) => i + 1);

// ─── Helpers ─────────────────────────────────────────────────────────────────

const ItemBadge = ({ status }) => {
  const cfg = ITEM_STATUS_CFG[status] || ITEM_STATUS_CFG.planeado;
  return (
    <span style={{ fontSize: 9, fontWeight: 700, letterSpacing: '0.07em', textTransform: 'uppercase', padding: '2px 7px', borderRadius: 4, background: cfg.bg, color: cfg.color, display: 'inline-block' }}>
      {cfg.label}
    </span>
  );
};

const PSelect = ({ value, onChange, options, placeholder = 'Seleccionar...' }) => (
  <select value={value || ''} onChange={e => onChange(e.target.value)}
    style={{ fontSize: 12, padding: '6px 10px', borderRadius: 6, background: 'var(--bg-sunken)', border: '1px solid var(--border)', color: value ? 'var(--text)' : 'var(--text-dim)', appearance: 'none', width: '100%' }}>
    <option value="">{placeholder}</option>
    {options.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
  </select>
);

async function campApiCall(url, options = {}) {
  let res;
  try {
    res = await fetch(url, { headers: { 'Content-Type': 'application/json' }, ...options });
  } catch (e) {
    throw new Error(`Erro de rede: ${e.message}`);
  }
  if (!res.ok) {
    let body = {};
    try { body = await res.json(); } catch {}
    throw new Error(body.error || `HTTP ${res.status}`);
  }
  return res.json();
}

const CAMP_STATUS_LABEL = {
  em_producao: 'Em Produção', publicado: 'Publicado',
  pending_executive: 'Aguarda Aprovação', em_aprovacao: 'Em Aprovação', aprovado: 'Aprovado',
  planeamento_aprovado: 'Planeamento', planeamento_gerado: 'Planeamento',
  funil_pendente: 'Funil', funil_gerado: 'Funil', funil_revisto: 'Funil', funil_aprovado: 'Funil',
  sdr_ai_pendente: 'SDR', sdr_ai_aprovado: 'SDR',
  prompts_pendente: 'Prompts', prompts_gerado: 'Prompts', prompts_aprovado: 'Aguarda Aprovação',
};

const GANTT_CANAL_COLOR = {
  meta_ads: 'var(--ai-500)', linkedin_ads: 'var(--ai-500)', google_ads_search: 'var(--danger)',
  google_ads_display: 'var(--success)', google_ads: 'var(--danger)',
  email: 'var(--ai-500)', email_externo: 'var(--ai-500)', email_html: 'var(--ai-500)',
  whatsapp: 'var(--success)', instagram: 'var(--accent)', facebook: 'var(--ai-500)',
  linkedin: 'var(--ai-500)', blog: 'var(--text-muted)', website: 'var(--text-muted)',
  youtube: 'var(--danger)', email_interno: 'var(--warn)', default: 'var(--text-muted)',
};

const PlanoDropdown = ({ label, value, options, onChange }) => {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const onClick = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onClick);
    return () => document.removeEventListener('mousedown', onClick);
  }, [open]);
  const current = options.find(o => o.value === value) || options[0];
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button onClick={() => setOpen(v => !v)} style={{
        background: 'var(--bg-elev)', color: 'var(--text)',
        border: '1px solid var(--border)', borderRadius: 6,
        padding: '6px 10px', fontSize: 11.5,
        display: 'inline-flex', alignItems: 'center', gap: 8,
        cursor: 'pointer', fontFamily: 'inherit',
      }}>
        <span style={{ color: 'var(--text-dim)', fontSize: 10, textTransform: 'uppercase', letterSpacing: '.06em', fontFamily: 'var(--font-mono)' }}>{label}</span>
        <span style={{ fontWeight: 500 }}>{current?.label || '—'}</span>
        <span style={{ color: 'var(--text-muted)', fontSize: 9 }}>▾</span>
      </button>
      {open && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 4px)', left: 0, zIndex: 50,
          background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 6,
          boxShadow: 'var(--shadow-md, 0 8px 24px color-mix(in oklch, var(--text) 12%, transparent))', minWidth: 160, padding: 4, maxHeight: 280, overflowY: 'auto',
        }}>
          {options.map(o => (
            <button key={o.value} onClick={() => { onChange(o.value); setOpen(false); }} style={{
              display: 'block', width: '100%', textAlign: 'left',
              background: o.value === value ? 'color-mix(in oklch, var(--ai-500) 12%, transparent)' : 'transparent',
              color: o.value === value ? 'var(--ai-500)' : 'var(--text)',
              border: 'none', padding: '7px 10px', borderRadius: 4,
              fontSize: 12, fontWeight: o.value === value ? 600 : 500,
              cursor: 'pointer', fontFamily: 'inherit',
            }}>{o.label}</button>
          ))}
        </div>
      )}
    </div>
  );
};

// ─── Item Drawer (direita) ────────────────────────────────────────────────────

const ItemDrawer = ({ item, planoId, onClose, onSaved, onDeleted, onPromote, promoting }) => {
  const [titulo, setTitulo] = React.useState(item.titulo || '');
  const [rationale, setRationale] = React.useState(item.rationale || '');
  const [canal, setCanal] = React.useState(item.canal || 'linkedin');
  const [contentType, setContentType] = React.useState(item.content_type || '');
  const [plannedDate, setPlannedDate] = React.useState(item.planned_date ? item.planned_date.split('T')[0] : '');
  const [status, setStatus] = React.useState(item.status || 'planeado');
  const [notes, setNotes] = React.useState(item.notes || '');
  const [saving, setSaving] = React.useState(false);

  async function handleSave() {
    setSaving(true);
    try {
      const res = await fetch(`/api/marketing/plano/${planoId}/itens/${item.id}`, {
        method: 'PATCH', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ titulo, rationale, canal, content_type: contentType, planned_date: plannedDate || null, status, notes }),
      });
      if (res.ok) { const updated = await res.json(); onSaved(updated); }
    } finally { setSaving(false); }
  }

  async function handleDelete() {
    await fetch(`/api/marketing/plano/${planoId}/itens/${item.id}`, { method: 'DELETE' });
    onDeleted(item.id);
  }

  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', zIndex: 49 }} />
      <div style={{ position: 'fixed', top: 0, right: 0, bottom: 0, width: 400, background: 'var(--bg)', borderLeft: '1px solid var(--border)', zIndex: 50, display: 'flex', flexDirection: 'column', boxShadow: '-4px 0 24px rgba(0,0,0,0.3)' }}>
        {/* Header */}
        <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', flexShrink: 0 }}>
          <div>
            <div style={{ fontSize: 10, fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', color: 'var(--text-dim)', marginBottom: 4 }}>
              SEMANA {item.week} · {(PC_CANAL_LABELS[item.canal] || item.canal).toUpperCase()}
            </div>
            <ItemBadge status={status} />
          </div>
          <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-dim)', padding: 2 }}>
            <Icon name="x" size={15} />
          </button>
        </div>
        {/* Body */}
        <div className="scrollbar" style={{ flex: 1, overflowY: 'auto', padding: 18 }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              <label style={{ fontSize: 10, fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Título</label>
              <textarea value={titulo} onChange={e => setTitulo(e.target.value)} rows={2} maxLength={100} style={{ fontSize: 13, padding: '7px 10px', borderRadius: 6, background: 'var(--bg-sunken)', border: '1px solid var(--border)', color: 'var(--text)', resize: 'vertical', width: '100%', boxSizing: 'border-box' }} />
              <div style={{ fontSize: 10, color: 'var(--text-dim)', textAlign: 'right' }}>{titulo.length}/100</div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              <label style={{ fontSize: 10, fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Rationale</label>
              <textarea value={rationale} onChange={e => setRationale(e.target.value)} rows={2} placeholder="Porquê este conteúdo nesta semana..." style={{ fontSize: 12, padding: '7px 10px', borderRadius: 6, background: 'var(--bg-sunken)', border: '1px solid var(--border)', color: 'var(--text)', resize: 'vertical', width: '100%', boxSizing: 'border-box' }} />
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                <label style={{ fontSize: 10, fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Canal</label>
                <PSelect value={canal} onChange={setCanal} options={CANAIS_OPTS.map(c => [c, PC_CANAL_LABELS[c]])} />
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                <label style={{ fontSize: 10, fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Formato</label>
                <input value={contentType} onChange={e => setContentType(e.target.value)} placeholder="carrossel, artigo..." style={{ fontSize: 12, padding: '6px 10px', borderRadius: 6, background: 'var(--bg-sunken)', border: '1px solid var(--border)', color: 'var(--text)', width: '100%', boxSizing: 'border-box' }} />
              </div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                <label style={{ fontSize: 10, fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Data planeada</label>
                <input type="date" value={plannedDate} onChange={e => setPlannedDate(e.target.value)} style={{ fontSize: 12, padding: '6px 10px', borderRadius: 6, background: 'var(--bg-sunken)', border: '1px solid var(--border)', color: 'var(--text)', width: '100%', boxSizing: 'border-box' }} />
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                <label style={{ fontSize: 10, fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Estado</label>
                <PSelect value={status} onChange={setStatus} options={Object.entries(ITEM_STATUS_CFG).filter(([k]) => k !== 'arquivado').map(([k, v]) => [k, v.label])} />
              </div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              <label style={{ fontSize: 10, fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Notas</label>
              <textarea value={notes} onChange={e => setNotes(e.target.value)} rows={2} placeholder="Notas internas..." style={{ fontSize: 12, padding: '7px 10px', borderRadius: 6, background: 'var(--bg-sunken)', border: '1px solid var(--border)', color: 'var(--text)', resize: 'vertical', width: '100%', boxSizing: 'border-box' }} />
            </div>
            {(item.briefing_id || item.campanha_id) && (
              <div style={{ borderTop: '1px solid var(--border)', paddingTop: 12, display: 'flex', flexDirection: 'column', gap: 6 }}>
                {item.briefing_id && (
                  <a href={`#screen=marketing&sub=briefings&id=${item.briefing_id}`} style={{ fontSize: 12, color: 'var(--accent)', textDecoration: 'none', display: 'flex', alignItems: 'center', gap: 5 }}>
                    <Icon name="external-link" size={12} /> Ver Briefing #{item.briefing_id}
                  </a>
                )}
                {item.campanha_id && (
                  <a href={`#screen=marketing&sub=campanhas&id=${item.campanha_id}`} style={{ fontSize: 12, color: 'var(--accent)', textDecoration: 'none', display: 'flex', alignItems: 'center', gap: 5 }}>
                    <Icon name="external-link" size={12} /> {item.campanha_titulo || 'Ver Campanha'}
                  </a>
                )}
              </div>
            )}
          </div>
        </div>
        {/* Footer */}
        <div style={{ padding: '12px 18px', borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexShrink: 0 }}>
          <button onClick={handleDelete} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'rgba(239,68,68,0.7)', fontSize: 12, display: 'flex', alignItems: 'center', gap: 4 }}>
            <Icon name="trash-2" size={13} /> Arquivar
          </button>
          <div style={{ display: 'flex', gap: 7 }}>
            {!item.briefing_id && (
              <button className="btn btn-sm" onClick={() => onPromote(item.id)} disabled={promoting} style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
                <Icon name="send" size={12} /> {promoting ? 'A criar...' : 'Criar Briefing'}
              </button>
            )}
            <button className="btn btn-sm btn-ai" onClick={handleSave} disabled={saving} style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
              <Icon name="check" size={12} /> {saving ? 'A guardar...' : 'Guardar'}
            </button>
          </div>
        </div>
      </div>
    </>
  );
};

// ─── Vista Calendário ─────────────────────────────────────────────────────────

const CalendarView = ({ itens, onItemClick }) => {
  const canais = [...new Set(itens.map(i => i.canal))].sort();
  if (!canais.length) return (
    <div style={{ padding: '48px 0', textAlign: 'center', color: 'var(--text-dim)', fontSize: 13 }}>
      Sem itens. Gera o plano com AI ou adiciona manualmente.
    </div>
  );
  const byKey = {};
  itens.forEach(i => { const k = `${i.canal}:${i.week}`; if (!byKey[k]) byKey[k] = []; byKey[k].push(i); });
  return (
    <div style={{ overflowX: 'auto' }}>
      <div style={{ display: 'grid', gridTemplateColumns: `130px repeat(13, minmax(68px, 1fr))`, gap: 3, minWidth: 1050 }}>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', padding: '5px 6px' }}>CANAL</div>
        {SEMANAS.map(w => <div key={w} style={{ fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)', padding: '5px 3px', textAlign: 'center' }}>S{w}</div>)}
        {canais.map(canal => (
          <React.Fragment key={canal}>
            <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-muted)', padding: '7px 6px', display: 'flex', alignItems: 'center', borderTop: '1px solid var(--border)' }}>
              {PC_CANAL_LABELS[canal] || canal}
            </div>
            {SEMANAS.map(w => {
              const cell = byKey[`${canal}:${w}`] || [];
              return (
                <div key={w} style={{ borderTop: '1px solid var(--border)', padding: '3px 2px', minHeight: 38, display: 'flex', flexDirection: 'column', gap: 2 }}>
                  {cell.map(it => {
                    const cfg = ITEM_STATUS_CFG[it.status] || ITEM_STATUS_CFG.planeado;
                    return (
                      <button key={it.id} onClick={() => onItemClick(it)} title={it.titulo}
                        style={{ background: cfg.bg, border: `1px solid ${cfg.color}33`, borderRadius: 3, padding: '2px 4px', cursor: 'pointer', fontSize: 10, color: cfg.color, fontWeight: 500, textAlign: 'left', lineHeight: 1.3, width: '100%', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                        {it.content_type ? `[${it.content_type}] ` : ''}{it.titulo}
                      </button>
                    );
                  })}
                </div>
              );
            })}
          </React.Fragment>
        ))}
      </div>
    </div>
  );
};

// ─── Vista Lista ──────────────────────────────────────────────────────────────

const ListView = ({ itens, onItemClick }) => {
  if (!itens.length) return <div style={{ padding: '48px 0', textAlign: 'center', color: 'var(--text-dim)', fontSize: 13 }}>Sem itens.</div>;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
      <div style={{ display: 'grid', gridTemplateColumns: '36px 100px 1fr 90px 80px', gap: 10, padding: '5px 10px', fontSize: 10, fontFamily: 'var(--font-mono)', letterSpacing: '0.06em', color: 'var(--text-dim)', borderBottom: '1px solid var(--border)' }}>
        <span>S.</span><span>CANAL</span><span>TÍTULO</span><span>FORMATO</span><span>ESTADO</span>
      </div>
      {itens.map(it => (
        <div key={it.id} onClick={() => onItemClick(it)}
          style={{ display: 'grid', gridTemplateColumns: '36px 100px 1fr 90px 80px', gap: 10, padding: '9px 10px', cursor: 'pointer', borderBottom: '1px solid var(--border)', transition: 'background 0.1s' }}
          onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-sunken)'}
          onMouseLeave={e => e.currentTarget.style.background = ''}>
          <span style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)', alignSelf: 'center' }}>S{it.week}</span>
          <span style={{ fontSize: 11, color: 'var(--text-muted)', alignSelf: 'center' }}>{PC_CANAL_LABELS[it.canal] || it.canal}</span>
          <div style={{ alignSelf: 'center' }}>
            <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--text)', lineHeight: 1.3 }}>{it.titulo}</div>
            {it.rationale && <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 1 }}>{it.rationale}</div>}
          </div>
          <span style={{ fontSize: 11, color: 'var(--text-muted)', alignSelf: 'center' }}>{it.content_type || '—'}</span>
          <div style={{ alignSelf: 'center' }}><ItemBadge status={it.status} /></div>
        </div>
      ))}
    </div>
  );
};

// ─── Vista Kanban ─────────────────────────────────────────────────────────────

const PC_KANBAN_COLS = ['planeado','em_briefing','em_campanha','em_producao','no_ar'];

const KanbanView = ({ itens, onItemClick }) => {
  const byStatus = {};
  PC_KANBAN_COLS.forEach(c => { byStatus[c] = []; });
  itens.forEach(it => { if (byStatus[it.status]) byStatus[it.status].push(it); });
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 10, alignItems: 'start' }}>
      {PC_KANBAN_COLS.map(col => {
        const cfg = ITEM_STATUS_CFG[col];
        return (
          <div key={col}>
            <div style={{ padding: '7px 10px', borderRadius: '7px 7px 0 0', background: cfg.bg, marginBottom: 5, display: 'flex', justifyContent: 'space-between' }}>
              <span style={{ fontSize: 10, fontWeight: 700, color: cfg.color, letterSpacing: '0.07em', textTransform: 'uppercase' }}>{cfg.label}</span>
              <span style={{ fontSize: 10, fontFamily: 'var(--font-mono)', color: cfg.color, opacity: 0.7 }}>{byStatus[col].length}</span>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
              {byStatus[col].map(it => (
                <div key={it.id} onClick={() => onItemClick(it)}
                  style={{ background: 'var(--bg-sunken)', border: '1px solid var(--border)', borderRadius: 7, padding: '9px 11px', cursor: 'pointer', transition: 'border-color 0.15s' }}
                  onMouseEnter={e => e.currentTarget.style.borderColor = 'var(--accent)'}
                  onMouseLeave={e => e.currentTarget.style.borderColor = 'var(--border)'}>
                  <div style={{ fontSize: 11, color: 'var(--text-dim)', marginBottom: 3 }}>S{it.week} · {PC_CANAL_LABELS[it.canal] || it.canal}</div>
                  <div style={{ fontSize: 12, fontWeight: 500, color: 'var(--text)', lineHeight: 1.35 }}>{it.titulo}</div>
                  {it.content_type && <div style={{ marginTop: 5, fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>{it.content_type}</div>}
                </div>
              ))}
              {!byStatus[col].length && <div style={{ padding: '14px 0', textAlign: 'center', color: 'var(--text-dim)', fontSize: 11 }}>—</div>}
            </div>
          </div>
        );
      })}
    </div>
  );
};

// ─── Dialog Gerador (Opus) ────────────────────────────────────────────────────

const GeneratorDialog = ({ planoId, brandName, quarter, year, onClose, onGenerated }) => {
  const [generating, setGenerating] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [result, setResult] = React.useState(null);

  async function handleGenerate() {
    setGenerating(true); setError(null); setResult(null);
    try {
      const res = await fetch(`/api/marketing/plano/${planoId}/generate`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({}) });
      const json = await res.json();
      if (!res.ok) { setError(json.error || 'Erro na geração'); return; }
      setResult(json);
    } catch { setError('Erro de rede'); }
    finally { setGenerating(false); }
  }

  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 59 }} />
      <div style={{ position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%,-50%)', width: 460, background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: 14, zIndex: 60, display: 'flex', flexDirection: 'column', boxShadow: '0 24px 64px rgba(0,0,0,0.4)' }}>
        <div style={{ padding: '18px 22px 14px', borderBottom: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <div style={{ fontSize: 10, fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', color: 'var(--text-dim)', marginBottom: 4 }}>AI · OPUS 4.7 EXTENDED THINKING</div>
            <h2 style={{ margin: 0, fontSize: 16, fontWeight: 600, color: 'var(--text)' }}>Gerar Plano Trimestral</h2>
          </div>
          <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-dim)', padding: 2 }}><Icon name="x" size={15} /></button>
        </div>
        <div style={{ padding: '18px 22px' }}>
          {!result && !generating && (
            <div>
              <div style={{ fontSize: 13, color: 'var(--text-muted)', lineHeight: 1.6, marginBottom: 16 }}>
                O Opus 4.7 vai analisar a estratégia de <strong style={{ color: 'var(--text)' }}>{brandName}</strong> e a KB de produto para gerar um plano editorial de 13 semanas para Q{quarter} {year}.
              </div>
              <div style={{ padding: '10px 14px', borderRadius: 8, background: 'rgba(56,89,208,0.08)', border: '1px solid rgba(56,89,208,0.2)', fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.5 }}>
                Processo demora 30-90 segundos. Os itens existentes serão substituídos.
              </div>
            </div>
          )}
          {generating && (
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12, padding: '24px 0' }}>
              <Icon name="brain" size={28} style={{ color: 'var(--accent)' }} />
              <div style={{ fontSize: 13, color: 'var(--text-muted)' }}>Opus a pensar sobre o plano...</div>
            </div>
          )}
          {error && <div style={{ padding: '10px 14px', borderRadius: 8, background: 'rgba(239,68,68,0.1)', border: '1px solid rgba(239,68,68,0.25)', fontSize: 12, color: '#ef4444' }}>{error}</div>}
          {result && (
            <div style={{ padding: '14px', borderRadius: 8, background: 'rgba(34,197,94,0.1)', border: '1px solid rgba(34,197,94,0.3)', display: 'flex', flexDirection: 'column', gap: 5 }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: '#22c55e' }}>Plano gerado</div>
              {result.titulo && <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{result.titulo}</div>}
              <div style={{ fontSize: 11, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>{result.itens_count} itens criados</div>
            </div>
          )}
        </div>
        <div style={{ padding: '14px 22px', borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'flex-end', gap: 7 }}>
          {result ? (
            <button className="btn btn-sm btn-ai" onClick={() => { onGenerated(); onClose(); }} style={{ display: 'flex', alignItems: 'center', gap: 5 }}>Ver Plano</button>
          ) : (
            <>
              <button className="btn btn-sm" onClick={onClose} disabled={generating}>Cancelar</button>
              <button className="btn btn-sm btn-ai" onClick={handleGenerate} disabled={generating} style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
                <Icon name="sparkles" size={12} /> {generating ? 'A gerar...' : 'Gerar com Opus'}
              </button>
            </>
          )}
        </div>
      </div>
    </>
  );
};

// ─── Dialog Criar Plano ───────────────────────────────────────────────────────

const CreateDialog = ({ brands, onCreated, onClose }) => {
  const [brandId, setBrandId] = React.useState(brands[0]?.id || '');
  const [year, setYear] = React.useState(2026);
  const [quarter, setQuarter] = React.useState(3);
  const [creating, setCreating] = React.useState(false);

  async function handleCreate() {
    setCreating(true);
    try {
      const res = await fetch('/api/marketing/plano', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ brand_id: brandId, year, quarter }) });
      const json = await res.json();
      if (json.id) onCreated(json.id);
    } finally { setCreating(false); }
  }

  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 59 }} />
      <div style={{ position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%,-50%)', width: 340, background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: 12, zIndex: 60, padding: 22, display: 'flex', flexDirection: 'column', gap: 14 }}>
        <h3 style={{ margin: 0, fontSize: 15, fontWeight: 600, color: 'var(--text)' }}>Novo Plano</h3>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <div>
            <label style={{ fontSize: 10, fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.06em', display: 'block', marginBottom: 4 }}>Marca</label>
            <PSelect value={String(brandId)} onChange={v => setBrandId(Number(v))} options={brands.map(b => [String(b.id), b.name])} />
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <div>
              <label style={{ fontSize: 10, fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.06em', display: 'block', marginBottom: 4 }}>Ano</label>
              <PSelect value={String(year)} onChange={v => setYear(Number(v))} options={ANOS.map(y => [String(y), String(y)])} />
            </div>
            <div>
              <label style={{ fontSize: 10, fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.06em', display: 'block', marginBottom: 4 }}>Trimestre</label>
              <PSelect value={String(quarter)} onChange={v => setQuarter(Number(v))} options={TRIMESTRES.map(q => [String(q), `Q${q}`])} />
            </div>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 7, justifyContent: 'flex-end' }}>
          <button className="btn btn-sm" onClick={onClose}>Cancelar</button>
          <button className="btn btn-sm btn-ai" onClick={handleCreate} disabled={creating} style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
            {creating ? 'A criar...' : 'Criar Plano'}
          </button>
        </div>
      </div>
    </>
  );
};

// ─── Detalhe do Plano ─────────────────────────────────────────────────────────

const PlanoDetail = ({ planoId, onBack }) => {
  const [plano, setPlano] = React.useState(null);
  const [view, setView] = React.useState('Calendário');
  const [activeItem, setActiveItem] = React.useState(null);
  const [showGenerator, setShowGenerator] = React.useState(false);
  const [promoting, setPromoting] = React.useState(false);

  const fetchPlano = React.useCallback(() => {
    fetch(`/api/marketing/plano/${planoId}`).then(r => r.json()).then(setPlano);
  }, [planoId]);

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

  function handleItemSaved(updated) {
    setPlano(p => p ? { ...p, itens: p.itens.map(i => i.id === updated.id ? updated : i) } : p);
    setActiveItem(updated);
  }

  function handleItemDeleted(id) {
    setPlano(p => p ? { ...p, itens: p.itens.filter(i => i.id !== id) } : p);
    setActiveItem(null);
  }

  async function handlePromote(itemId) {
    setPromoting(true);
    try {
      const res = await fetch(`/api/marketing/plano/${planoId}/itens/${itemId}/promote`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({}) });
      const json = await res.json();
      if (json.briefing_id) { fetchPlano(); }
    } finally { setPromoting(false); }
  }

  if (!plano) return <div style={{ padding: 32, color: 'var(--text-dim)', fontSize: 13 }}>A carregar...</div>;

  const scfg = PLANO_STATUS_CFG[plano.status] || PLANO_STATUS_CFG.rascunho;
  const itens = plano.itens || [];

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* Header */}
      <div style={{ padding: '16px 24px 0', flexShrink: 0 }}>
        <button onClick={onBack} style={{ background: 'none', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 5, color: 'var(--text-dim)', fontSize: 12, marginBottom: 12, padding: 0 }}>
          <Icon name="arrow-left" size={13} /> Plano de Comunicação
        </button>
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 12 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
            <div style={{ width: 10, height: 10, borderRadius: '50%', background: plano.brand_color }} />
            <div>
              <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em' }}>{plano.brand_name} · Q{plano.quarter} {plano.year}</div>
              <h1 className="font-display" style={{ margin: '2px 0 0', fontSize: 18, fontWeight: 600, letterSpacing: '-0.015em' }}>{plano.titulo || `Plano Q${plano.quarter} ${plano.year}`}</h1>
            </div>
            <span style={{ fontSize: 9, fontWeight: 700, letterSpacing: '0.07em', textTransform: 'uppercase', padding: '3px 8px', borderRadius: 5, background: scfg.bg, color: scfg.color }}>{scfg.label}</span>
          </div>
          <div style={{ display: 'flex', gap: 6 }}>
            <button className="btn btn-sm btn-ai" onClick={() => setShowGenerator(true)} style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
              <Icon name="sparkles" size={12} /> Gerar com Opus
            </button>
          </div>
        </div>
        {plano.estrategia_resumo && (
          <div style={{ fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.6, maxWidth: 700, marginBottom: 12, padding: '9px 13px', borderRadius: 8, background: 'var(--bg-sunken)', border: '1px solid var(--border)' }}>
            {plano.estrategia_resumo}
          </div>
        )}
        {/* Stats */}
        <div style={{ display: 'flex', gap: 18, marginBottom: 12 }}>
          {[['Total', itens.length], ['No Ar', itens.filter(i => i.status === 'no_ar').length], ['Em Produção', itens.filter(i => i.status === 'em_producao').length], ['Planeado', itens.filter(i => i.status === 'planeado').length]].map(([l, v]) => (
            <div key={l}>
              <div style={{ fontSize: 18, fontWeight: 700, color: 'var(--text)', fontFamily: 'var(--font-mono)' }}>{v}</div>
              <div style={{ fontSize: 10, color: 'var(--text-dim)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>{l}</div>
            </div>
          ))}
        </div>
        {/* View tabs */}
        <div style={{ display: 'flex', gap: 1, borderBottom: '1px solid var(--border)' }}>
          {['Calendário','Lista','Kanban'].map(v => (
            <button key={v} onClick={() => setView(v)} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: '7px 13px', fontSize: 12, fontWeight: 500, color: view === v ? 'var(--text)' : 'var(--text-dim)', borderBottom: view === v ? '2px solid var(--accent)' : '2px solid transparent', marginBottom: -1, transition: 'color 0.15s' }}>
              {v}
            </button>
          ))}
        </div>
      </div>
      {/* Content */}
      <div className="scrollbar" style={{ flex: 1, overflowY: 'auto', padding: '18px 24px 48px' }}>
        {view === 'Calendário' && <CalendarView itens={itens} onItemClick={setActiveItem} />}
        {view === 'Lista'      && <ListView itens={itens} onItemClick={setActiveItem} />}
        {view === 'Kanban'     && <KanbanView itens={itens} onItemClick={setActiveItem} />}
      </div>
      {activeItem && <ItemDrawer item={activeItem} planoId={planoId} onClose={() => setActiveItem(null)} onSaved={handleItemSaved} onDeleted={handleItemDeleted} onPromote={handlePromote} promoting={promoting} />}
      {showGenerator && <GeneratorDialog planoId={planoId} brandName={plano.brand_name} quarter={plano.quarter} year={plano.year} onClose={() => setShowGenerator(false)} onGenerated={fetchPlano} />}
    </div>
  );
};

// ─── Lista de Planos ──────────────────────────────────────────────────────────

const PlanoList = ({ onSelect, brandSlug, brands: brandsProp }) => {
  const [planos, setPlanos] = React.useState([]);
  const [brandsLocal, setBrandsLocal] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [showCreate, setShowCreate] = React.useState(false);
  const [filterYear, setFilterYear] = React.useState('');
  const brands = brandsProp?.length ? brandsProp : brandsLocal;

  React.useEffect(() => {
    Promise.all([
      fetch('/api/marketing/plano').then(r => r.json()),
      brandsProp?.length ? Promise.resolve(brandsProp) : fetch('/api/marketing/brands').then(r => r.json()),
    ]).then(([p, b]) => { setPlanos(p); if (!brandsProp?.length) setBrandsLocal(b); }).finally(() => setLoading(false));
  }, []);

  const filtered = planos.filter(p => {
    if (brandSlug && brandSlug !== 'todas' && p.brand_slug !== brandSlug) return false;
    if (filterYear && String(p.year) !== filterYear) return false;
    return true;
  });
  const createBrands = brands.filter(b => b.slug && b.slug !== 'todas');

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      {/* Toolbar */}
      <div style={{ display: 'flex', gap: 7, alignItems: 'center' }}>
        <PSelect value={filterYear} onChange={setFilterYear} options={ANOS.map(y => [String(y), String(y)])} placeholder="Todos os anos" />
        <div style={{ flex: 1 }} />
        <button className="btn btn-sm btn-ai" onClick={() => setShowCreate(true)} style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
          <Icon name="plus" size={12} /> Novo Plano
        </button>
      </div>
      {/* List */}
      {loading ? (
        <div style={{ color: 'var(--text-dim)', fontSize: 13 }}>A carregar...</div>
      ) : !filtered.length ? (
        <div style={{ padding: '48px 0', textAlign: 'center', color: 'var(--text-dim)', fontSize: 13 }}>
          <Icon name="calendar" size={32} style={{ margin: '0 auto 12px', display: 'block', opacity: 0.4 }} />
          Sem planos. Cria o primeiro.
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
          {filtered.map(p => {
            const cfg = PLANO_STATUS_CFG[p.status] || PLANO_STATUS_CFG.rascunho;
            return (
              <div key={p.id} onClick={() => onSelect(p.id)}
                style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '13px 15px', borderRadius: 10, cursor: 'pointer', background: 'var(--bg-sunken)', border: '1px solid var(--border)', transition: 'border-color 0.15s' }}
                onMouseEnter={e => e.currentTarget.style.borderColor = 'var(--accent)'}
                onMouseLeave={e => e.currentTarget.style.borderColor = 'var(--border)'}>
                <div style={{ width: 10, height: 10, borderRadius: '50%', background: p.brand_color, flexShrink: 0 }} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)' }}>{p.titulo || `Q${p.quarter} ${p.year} — ${p.brand_name}`}</div>
                  <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 2 }}>{p.total_itens} itens · {p.itens_no_ar} no ar</div>
                </div>
                <span style={{ fontSize: 9, fontWeight: 700, letterSpacing: '0.07em', textTransform: 'uppercase', padding: '3px 8px', borderRadius: 5, background: cfg.bg, color: cfg.color }}>{cfg.label}</span>
                <Icon name="chevron-right" size={13} style={{ color: 'var(--text-dim)' }} />
              </div>
            );
          })}
        </div>
      )}
      {showCreate && <CreateDialog brands={createBrands} onCreated={id => { setShowCreate(false); onSelect(id); }} onClose={() => setShowCreate(false)} />}
    </div>
  );
};

// ─── Gantt agregado (read-only, UX da tab Planeamento) ────────────────────────

const AgregadoCampanhasGantt = ({ itens, year, onItemClick }) => {
  const [ganttZoom, setGanttZoom] = React.useState('weeks');
  const [tooltip, setTooltip] = React.useState(null);

  const toD = (s) => { const d = new Date(s); d.setHours(0, 0, 0, 0); return d; };
  const fmtD = (d) => d.toLocaleDateString('pt-PT', { day: '2-digit', month: 'short' });
  const getISOWeek = (d) => {
    const dt = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
    dt.setUTCDate(dt.getUTCDate() + 4 - (dt.getUTCDay() || 7));
    const y = new Date(Date.UTC(dt.getUTCFullYear(), 0, 1));
    return Math.ceil((((dt - y) / 864e5) + 1) / 7);
  };
  const shortLabel = (item) => {
    const titulo = item.titulo || '';
    const ctyM = titulo.match(/^\s*(?:⚠\s*)?\[([A-Z0-9\-]{1,10})\]/);
    const cty = ctyM ? ctyM[1] : '';
    const codeM = titulo.match(/\b(AD|EM|WA|INT|BL|LP|PC)-\d+\b/);
    const code = codeM ? codeM[0] : '';
    const tema = (item.subtitulo || '').split(/[.·—]/)[0].trim().slice(0, 28)
      || CAMP_STATUS_LABEL[item.campanha_status] || item.campanha_titulo || '—';
    const parts = [];
    if (cty) parts.push(`[${cty}]`);
    if (code) parts.push(code);
    return parts.length ? `${parts.join(' ')} · ${tema}` : tema;
  };

  const rows = (itens || []).map((item, i) => {
    const ds = item.planned_date;
    if (!ds) return null;
    const start = toD(ds.slice(0, 10));
    const end = item.planned_end_date ? toD(item.planned_end_date.slice(0, 10)) : start;
    const canal = item.canal || 'social';
    return {
      id: `${item.campanha_id}_${i}`,
      item,
      label: shortLabel(item),
      canal,
      color: GANTT_CANAL_COLOR[canal] || GANTT_CANAL_COLOR.default,
      start, end,
      is_interno: item.content_type === 'briefing_interno' || (canal || '').includes('interno'),
      needs_review: !!item.needs_review,
      tipo: item.planned_end_date && item.planned_end_date !== item.planned_date ? 'periodo' : 'evento',
    };
  }).filter(Boolean);

  const CATEGORIES = [
    { id: 'interno', label: 'Comunicação Interna', color: 'var(--warn)', match: r => r.is_interno || (r.canal || '').includes('interno') },
    { id: 'paid', label: 'Paid Media', color: 'var(--ai-500)', match: r => ['meta_ads','linkedin_ads','google_ads_search','google_ads_display','google_ads','muppi_led'].includes(r.canal) && r.item.content_type !== 'social_post' },
    { id: 'email', label: 'Email', color: 'var(--ai-500)', match: r => ['email','email_externo','email_html'].includes(r.canal) },
    { id: 'social', label: 'Social Media', color: 'var(--accent)', match: r => ['instagram','facebook','linkedin','social'].includes(r.canal) || r.item.content_type === 'social_post' },
    { id: 'whatsapp', label: 'WhatsApp', color: 'var(--success)', match: r => r.canal === 'whatsapp' || r.item.content_type === 'wa_message' },
    { id: 'website', label: 'Blog', color: 'var(--text-muted)', match: r => ['site','website','blog','youtube'].includes(r.canal) || ['artigo_blog','blog_post','artigo'].includes(r.item.content_type) },
  ];
  const grouped = CATEGORIES.map(cat => ({ ...cat, rows: rows.filter(r => cat.match(r)).sort((a, b) => a.start - b.start) })).filter(c => c.rows.length);
  const allRows = grouped.flatMap(c => [{ ...c, isCategory: true }, ...c.rows]);
  if (!allRows.length) {
    return (
      <div style={{ background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 8, padding: '48px 24px', textAlign: 'center', color: 'var(--text-muted)', fontSize: 13 }}>
        Sem peças calendarizadas neste ano para os filtros actuais.
      </div>
    );
  }

  const today = new Date(); today.setHours(0, 0, 0, 0);
  const gStart = new Date(year, 0, 1);
  const gEnd = new Date(year, 11, 31);
  const totalDays = Math.ceil((gEnd - gStart) / 864e5);
  const PX_PER_DAY = { days: 40, weeks: 14, months: 5 };
  const pxPerDay = PX_PER_DAY[ganttZoom] || 14;
  const totalWidth = Math.max(totalDays * pxPerDay, 600);
  const px = (d) => Math.max(0, Math.min(totalWidth, ((d - gStart) / 864e5) * pxPerDay));
  const todayPx = px(today);
  const LABEL_W = 280;
  const ROW_H = 36;

  const monthMarkers = [];
  const mc = new Date(gStart.getFullYear(), gStart.getMonth(), 1);
  while (mc <= gEnd) {
    monthMarkers.push({
      key: mc.toISOString().slice(0, 7),
      label: mc.toLocaleDateString('pt-PT', { month: 'long' }).charAt(0).toUpperCase() + mc.toLocaleDateString('pt-PT', { month: 'long' }).slice(1),
      px: px(mc),
      width: Math.max(0, px(new Date(mc.getFullYear(), mc.getMonth() + 1, 1)) - px(mc)),
    });
    mc.setMonth(mc.getMonth() + 1);
  }
  const headerMarkers = [];
  const cur = new Date(gStart);
  if (ganttZoom === 'days') {
    while (cur <= gEnd) {
      headerMarkers.push({ key: cur.toISOString().slice(0, 10), label: String(cur.getDate()), weekNum: cur.getDay() === 1 ? getISOWeek(cur) : null, px: px(cur), isWeekend: cur.getDay() === 0 || cur.getDay() === 6 });
      cur.setDate(cur.getDate() + 1);
    }
  } else {
    while (cur <= gEnd) {
      const mon = new Date(cur); mon.setDate(cur.getDate() - ((cur.getDay() + 6) % 7));
      const key = mon.toISOString().slice(0, 10);
      if (!headerMarkers.length || headerMarkers[headerMarkers.length - 1].key !== key) {
        headerMarkers.push({ key, label: ganttZoom === 'months' ? `S${getISOWeek(mon)}` : `S${getISOWeek(mon)} · ${fmtD(mon)}`, px: px(mon) });
      }
      cur.setDate(cur.getDate() + 7);
    }
  }

  return (
    <div style={{ background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 8, overflow: 'hidden' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '8px 12px', borderBottom: '1px solid var(--border)', background: 'var(--bg-sunken)', justifyContent: 'flex-end' }}>
        <span style={{ fontSize: 10, color: 'var(--text-dim)', marginRight: 4 }}>Zoom:</span>
        {[['days', 'Dias'], ['weeks', 'Semanas'], ['months', 'Meses']].map(([z, l]) => (
          <button key={z} className="btn" onClick={() => setGanttZoom(z)} style={{
            height: 28, padding: '0 10px', fontSize: 11,
            background: ganttZoom === z ? 'var(--ai-500)' : 'var(--bg-elev)',
            color: ganttZoom === z ? 'var(--bg-elev)' : 'var(--text-muted)',
            borderColor: ganttZoom === z ? 'var(--ai-500)' : 'var(--border)',
          }}>{l}</button>
        ))}
      </div>
      <div className="scrollbar" style={{ overflowX: 'auto' }} ref={el => {
        if (el && el._ganttZoom !== ganttZoom) {
          el.scrollLeft = Math.max(0, todayPx - 200);
          el._ganttZoom = ganttZoom;
        }
      }}>
        <div style={{ width: LABEL_W + totalWidth, minWidth: LABEL_W + 400 }}>
          <div style={{ position: 'sticky', top: 0, zIndex: 20 }}>
            <div style={{ display: 'flex', borderBottom: '1px solid var(--border)', background: 'var(--bg-sunken)' }}>
              <div style={{ width: LABEL_W, flexShrink: 0, borderRight: '1px solid var(--border)', position: 'sticky', left: 0, background: 'var(--bg-sunken)', zIndex: 21, height: 22, display: 'flex', alignItems: 'center', padding: '0 12px' }}>
                <span style={{ fontSize: 9, fontWeight: 700, fontFamily: 'var(--font-mono)', textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--text-dim)' }}>Marca / Peça</span>
              </div>
              <div style={{ flex: 1, position: 'relative', height: 22 }}>
                {monthMarkers.map(m => (
                  <div key={m.key} style={{ position: 'absolute', left: m.px, top: 0, bottom: 0, borderLeft: '1px solid var(--border)', paddingLeft: 6, display: 'flex', alignItems: 'center', overflow: 'hidden', width: m.width }}>
                    <span style={{ fontSize: 10, fontWeight: 700, fontFamily: 'var(--font-mono)', color: 'var(--text)', whiteSpace: 'nowrap' }}>{m.label}</span>
                  </div>
                ))}
                <div style={{ position: 'absolute', left: todayPx, top: 0, bottom: 0, width: pxPerDay, background: 'color-mix(in oklch, var(--danger) 15%, transparent)', zIndex: 10 }} />
              </div>
            </div>
            <div style={{ display: 'flex', borderBottom: '2px solid var(--border)', background: 'var(--bg-sunken)' }}>
              <div style={{ width: LABEL_W, flexShrink: 0, borderRight: '1px solid var(--border)', position: 'sticky', left: 0, background: 'var(--bg-sunken)', zIndex: 21, height: 20 }} />
              <div style={{ flex: 1, position: 'relative', height: 20 }}>
                {headerMarkers.map(w => (
                  <div key={w.key} style={{ position: 'absolute', left: w.px, top: 0, bottom: 0, borderLeft: '1px solid var(--border)', paddingLeft: 3, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
                    {w.weekNum != null && <span style={{ fontSize: 7, fontFamily: 'var(--font-mono)', color: 'var(--ai-500)', fontWeight: 700, lineHeight: 1 }}>S{w.weekNum}</span>}
                    <span style={{ fontSize: 8, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)', whiteSpace: 'nowrap', opacity: w.isWeekend ? 0.5 : 1, lineHeight: 1 }}>{w.label}</span>
                  </div>
                ))}
                <div style={{ position: 'absolute', left: todayPx, top: 0, bottom: 0, width: pxPerDay, background: 'color-mix(in oklch, var(--danger) 12%, transparent)', zIndex: 10 }} />
              </div>
            </div>
          </div>
          {allRows.map(gr => {
            if (gr.isCategory) {
              return (
                <div key={'cat_' + gr.id} style={{ display: 'flex', borderBottom: '1px solid var(--border)', background: 'var(--bg-sunken)', height: 26 }}>
                  <div style={{ width: LABEL_W, flexShrink: 0, padding: '0 14px', display: 'flex', alignItems: 'center', gap: 6, borderRight: '1px solid var(--border)', position: 'sticky', left: 0, background: 'var(--bg-sunken)', zIndex: 10 }}>
                    <span style={{ width: 3, height: 12, borderRadius: 2, background: gr.color, flexShrink: 0 }} />
                    <span style={{ fontSize: 10, fontWeight: 700, fontFamily: 'var(--font-mono)', textTransform: 'uppercase', letterSpacing: '.06em', color: gr.color }}>{gr.label}</span>
                  </div>
                  <div style={{ flex: 1, position: 'relative' }}>
                    <div style={{ position: 'absolute', left: todayPx, top: 0, bottom: 0, width: pxPerDay, background: 'color-mix(in oklch, var(--danger) 8%, transparent)' }} />
                  </div>
                </div>
              );
            }
            const it = gr.item;
            const lPx = px(gr.start);
            const rPx = gr.tipo === 'periodo' ? px(new Date(gr.end.getTime() + 864e5)) : lPx + pxPerDay;
            const wPx = Math.max(rPx - lPx, 2);
            return (
              <div key={gr.id} style={{ display: 'flex', borderBottom: '1px solid var(--border)', minHeight: ROW_H, background: 'var(--bg-elev)' }}>
                <div style={{ width: LABEL_W, flexShrink: 0, padding: '0 12px 0 22px', display: 'flex', alignItems: 'center', gap: 7, borderRight: '1px solid var(--border)', position: 'sticky', left: 0, background: 'var(--bg-elev)', zIndex: 10 }}>
                  <span style={{ width: 8, height: 8, borderRadius: '50%', background: it.brand_color || 'var(--text-muted)', flexShrink: 0 }} />
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)', letterSpacing: '.04em', textTransform: 'uppercase', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.brand_name} · {CAMP_STATUS_LABEL[it.campanha_status] || it.campanha_status}</div>
                    <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{gr.label}</div>
                  </div>
                </div>
                <div style={{ flex: 1, position: 'relative', minHeight: ROW_H }}>
                  {headerMarkers.map(w => <div key={w.key} style={{ position: 'absolute', left: w.px, top: 0, bottom: 0, borderLeft: '1px solid var(--border)', opacity: 0.2 }} />)}
                  <div style={{ position: 'absolute', left: todayPx, top: 0, bottom: 0, width: pxPerDay, background: 'color-mix(in oklch, var(--danger) 10%, transparent)', zIndex: 5 }} />
                  <button
                    onClick={() => onItemClick && onItemClick(it)}
                    onMouseEnter={e => setTooltip({ x: e.clientX, y: e.clientY, gr })}
                    onMouseMove={e => setTooltip(t => t ? { ...t, x: e.clientX, y: e.clientY } : null)}
                    onMouseLeave={() => setTooltip(null)}
                    style={{
                      position: 'absolute', left: lPx, width: wPx, top: 6, bottom: 6,
                      background: gr.needs_review ? 'var(--warn)' : gr.color,
                      border: 'none', borderRadius: 3, cursor: 'pointer', zIndex: 6,
                      display: 'flex', alignItems: 'center', paddingLeft: wPx > 20 ? 8 : 0, overflow: 'hidden',
                      opacity: 0.88,
                    }}>
                    {wPx > 50 && <span style={{ fontSize: 9, color: 'var(--bg-elev)', fontWeight: 700, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.brand_name} · {gr.label}</span>}
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      </div>
      <div style={{ padding: '8px 14px', borderTop: '1px solid var(--border)', display: 'flex', gap: 16, flexWrap: 'wrap', background: 'var(--bg-sunken)' }}>
        <span style={{ fontSize: 10, color: 'var(--text-muted)', display: 'inline-flex', alignItems: 'center', gap: 4 }}><span style={{ width: 12, height: 3, background: 'var(--danger)', borderRadius: 1 }} /> Hoje</span>
        <span style={{ fontSize: 10, color: 'var(--text-muted)' }}>{rows.length} peças</span>
      </div>
      {tooltip && (() => {
        const { gr } = tooltip;
        const it = gr.item;
        const left = tooltip.x + 16 + 320 > window.innerWidth ? tooltip.x - 328 : tooltip.x + 16;
        const top = tooltip.y + 16 + 180 > window.innerHeight ? tooltip.y - 188 : tooltip.y + 16;
        return (
          <div style={{ position: 'fixed', left, top, width: 320, background: 'var(--bg-elev)', borderRadius: 10, boxShadow: 'var(--shadow-md, 0 8px 32px color-mix(in oklch, var(--text) 18%, transparent))', border: '1px solid var(--border)', zIndex: 99999, pointerEvents: 'none', overflow: 'hidden' }}>
            <div style={{ background: 'var(--bg-sunken)', padding: '10px 14px', borderBottom: '1px solid var(--border)' }}>
              <div style={{ fontSize: 9, fontWeight: 700, fontFamily: 'var(--font-mono)', textTransform: 'uppercase', letterSpacing: '.08em', color: 'var(--text-dim)', marginBottom: 3 }}>{it.brand_name} · {CAMP_STATUS_LABEL[it.campanha_status] || it.campanha_status}</div>
              <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--text)', lineHeight: 1.3 }}>{it.campanha_titulo}</div>
            </div>
            <div style={{ padding: '10px 14px', fontSize: 11, color: 'var(--text)', lineHeight: 1.45 }}>
              <div>{gr.label}</div>
              <div style={{ marginTop: 6, fontFamily: 'var(--font-mono)', color: 'var(--text-muted)' }}>{fmtD(gr.start)}{gr.tipo === 'periodo' && gr.end > gr.start ? ` → ${fmtD(gr.end)}` : ''}</div>
            </div>
          </div>
        );
      })()}
    </div>
  );
};

const AgregadoCalendarView = ({ itens, onItemClick }) => {
  const canais = [...new Set(itens.map(i => i.canal))].sort();
  if (!canais.length) {
    return <div style={{ padding: '48px 0', textAlign: 'center', color: 'var(--text-dim)', fontSize: 13 }}>Sem itens editoriais neste trimestre.</div>;
  }
  const byKey = {};
  itens.forEach(i => { const k = `${i.canal}:${i.week}`; if (!byKey[k]) byKey[k] = []; byKey[k].push(i); });
  return (
    <div style={{ overflowX: 'auto', background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 8, padding: 12 }}>
      <div style={{ display: 'grid', gridTemplateColumns: '130px repeat(13, minmax(68px, 1fr))', gap: 3, minWidth: 1050 }}>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', padding: '5px 6px' }}>CANAL</div>
        {SEMANAS.map(w => <div key={w} style={{ fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)', padding: '5px 3px', textAlign: 'center' }}>S{w}</div>)}
        {canais.map(canal => (
          <React.Fragment key={canal}>
            <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-muted)', padding: '7px 6px', display: 'flex', alignItems: 'center', borderTop: '1px solid var(--border)' }}>
              {PC_CANAL_LABELS[canal] || canal}
            </div>
            {SEMANAS.map(w => {
              const cell = byKey[`${canal}:${w}`] || [];
              return (
                <div key={w} style={{ borderTop: '1px solid var(--border)', padding: '3px 2px', minHeight: 38, display: 'flex', flexDirection: 'column', gap: 2 }}>
                  {cell.map(it => {
                    const cfg = ITEM_STATUS_CFG[it.status] || ITEM_STATUS_CFG.planeado;
                    return (
                      <button key={it.id} onClick={() => onItemClick(it)} title={`${it.brand_name} · ${it.titulo}`}
                        style={{ background: cfg.bg, border: '1px solid var(--border)', borderRadius: 3, padding: '2px 4px', cursor: 'pointer', fontSize: 10, color: cfg.color, fontWeight: 500, textAlign: 'left', lineHeight: 1.3, width: '100%', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', display: 'flex', alignItems: 'center', gap: 4 }}>
                        <span style={{ width: 6, height: 6, borderRadius: '50%', background: it.brand_color || 'var(--text-muted)', flexShrink: 0 }} />
                        <span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.brand_name} · {it.titulo}</span>
                      </button>
                    );
                  })}
                </div>
              );
            })}
          </React.Fragment>
        ))}
      </div>
    </div>
  );
};

const PlanoKpiStrip = ({ cards, activeKey, onSelect }) => (
  <div style={{ display: 'flex', gap: 12 }}>
    {cards.map((k, i) => {
      const isActive = activeKey != null && k.key === activeKey;
      return (
        <div key={k.key || i} onClick={() => onSelect && onSelect(k.key)}
          style={{
            flex: '1 1 0', background: 'var(--bg-elev)',
            border: `1px solid ${isActive ? 'var(--ai-500)' : 'var(--border)'}`,
            borderRadius: 8, padding: '12px 16px 0',
            display: 'flex', flexDirection: 'column', gap: 4, overflow: 'hidden',
            cursor: onSelect ? 'pointer' : 'default',
          }}>
          <div style={{ fontSize: 9.5, fontWeight: 600, letterSpacing: '0.10em', textTransform: 'uppercase', color: isActive ? 'var(--ai-500)' : 'var(--text-muted)', fontFamily: 'var(--font-mono)', whiteSpace: 'nowrap' }}>{k.label}</div>
          <div style={{ fontSize: 22, fontWeight: 700, fontFamily: 'var(--font-display)', color: k.accent || 'var(--text)', lineHeight: 1, paddingBottom: 10 }}>{k.value}</div>
          <div style={{ height: 3, background: 'var(--bg-sunken)', overflow: 'hidden' }}>
            <div style={{ height: '100%', width: `${(k.fill || 0) * 100}%`, background: k.accent || 'var(--ai-500)' }} />
          </div>
        </div>
      );
    })}
  </div>
);

const TodasMarcasView = ({ onSelectPlano }) => {
  const [subView, setSubView] = React.useState('calendario');
  const [year, setYear] = React.useState(2026);
  const [quarter, setQuarter] = React.useState(3);
  const [pipeline, setPipeline] = React.useState(false);
  const [ganttItens, setGanttItens] = React.useState([]);
  const [semanas, setSemanas] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState('');

  const loadGantt = React.useCallback(() => {
    setLoading(true); setError('');
    campApiCall(`/api/marketing/campanhas-gantt-agregado?year=${year}&pipeline=${pipeline ? 1 : 0}`)
      .then(d => setGanttItens(d.itens || []))
      .catch(e => setError(e.message))
      .finally(() => setLoading(false));
  }, [year, pipeline]);

  const loadEditorial = React.useCallback(() => {
    setLoading(true); setError('');
    campApiCall(`/api/marketing/planos-agregado?year=${year}&quarter=${quarter}`)
      .then(d => setSemanas(d.semanas || []))
      .catch(e => setError(e.message))
      .finally(() => setLoading(false));
  }, [year, quarter]);

  React.useEffect(() => {
    if (subView === 'calendario') loadGantt();
    else loadEditorial();
  }, [subView, loadGantt, loadEditorial]);

  const editorialItens = React.useMemo(() => semanas.flatMap(s => s.itens || []), [semanas]);
  const campanhasUnicas = React.useMemo(() => new Set(ganttItens.map(i => i.campanha_id)), [ganttItens]);
  const emProd = new Set(ganttItens.filter(i => i.campanha_status === 'em_producao').map(i => i.campanha_id)).size;
  const pub = new Set(ganttItens.filter(i => i.campanha_status === 'publicado').map(i => i.campanha_id)).size;
  const kpiCards = subView === 'calendario'
    ? [
        { key: 'pecas', label: 'Peças', value: ganttItens.length, fill: 1, accent: 'var(--ai-500)' },
        { key: 'campanhas', label: 'Campanhas', value: campanhasUnicas.size, fill: campanhasUnicas.size ? 1 : 0, accent: 'var(--text)' },
        { key: 'prod', label: 'Em Produção', value: emProd, fill: campanhasUnicas.size ? emProd / campanhasUnicas.size : 0, accent: 'var(--success)' },
        { key: 'pub', label: 'Publicado', value: pub, fill: campanhasUnicas.size ? pub / campanhasUnicas.size : 0, accent: 'var(--ai-500)' },
      ]
    : [
        { key: 'total', label: 'Itens', value: editorialItens.length, fill: 1, accent: 'var(--ai-500)' },
        { key: 'planeado', label: 'Planeado', value: editorialItens.filter(i => i.status === 'planeado').length, fill: editorialItens.length ? editorialItens.filter(i => i.status === 'planeado').length / editorialItens.length : 0, accent: 'var(--text-muted)' },
        { key: 'briefing', label: 'Em Briefing', value: editorialItens.filter(i => i.status === 'em_briefing').length, fill: editorialItens.length ? editorialItens.filter(i => i.status === 'em_briefing').length / editorialItens.length : 0, accent: 'var(--warn)' },
        { key: 'noar', label: 'No Ar', value: editorialItens.filter(i => i.status === 'no_ar').length, fill: editorialItens.length ? editorialItens.filter(i => i.status === 'no_ar').length / editorialItens.length : 0, accent: 'var(--success)' },
      ];

  const openCampanha = (item) => {
    if (window.mktNavToSub) window.mktNavToSub('campanhas');
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 8 }}>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', alignItems: 'center' }}>
          {[['calendario', 'Calendário'], ['editorial', 'Editorial']].map(([id, label]) => (
            <button key={id} onClick={() => setSubView(id)} className="btn" style={{
              height: 30, padding: '0 12px', fontSize: 12,
              background: subView === id ? 'var(--ai-500)' : 'var(--bg-elev)',
              color: subView === id ? 'var(--bg-elev)' : 'var(--text-muted)',
              borderColor: subView === id ? 'var(--ai-500)' : 'var(--border)',
            }}>{label}</button>
          ))}
          <PlanoDropdown label="Ano" value={String(year)} onChange={v => setYear(Number(v))} options={ANOS.map(y => ({ value: String(y), label: String(y) }))} />
          {subView === 'editorial' && (
            <PlanoDropdown label="Trimestre" value={String(quarter)} onChange={v => setQuarter(Number(v))} options={TRIMESTRES.map(q => ({ value: String(q), label: `Q${q}` }))} />
          )}
          {subView === 'calendario' && (
            <button className="btn" onClick={() => setPipeline(p => !p)} style={{
              height: 30, padding: '0 12px', fontSize: 12,
              background: pipeline ? 'color-mix(in oklch, var(--ai-500) 12%, var(--bg-elev))' : 'var(--bg-elev)',
              color: pipeline ? 'var(--ai-500)' : 'var(--text-muted)',
              borderColor: pipeline ? 'var(--ai-500)' : 'var(--border)',
            }}>Incluir pipeline</button>
          )}
        </div>
        <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>
          {subView === 'calendario' ? `${ganttItens.length} peças` : `${editorialItens.length} itens`}
        </span>
      </div>
      <PlanoKpiStrip cards={kpiCards} />
      {error && (
        <div style={{ padding: '10px 14px', borderRadius: 8, background: 'color-mix(in oklch, var(--danger) 8%, var(--bg-elev))', border: '1px solid color-mix(in oklch, var(--danger) 25%, var(--border))', fontSize: 12, color: 'var(--danger)' }}>{error}</div>
      )}
      {loading ? (
        <div>{[1, 2, 3].map(i => <div key={i} style={{ height: 44, borderRadius: 6, background: 'var(--bg-sunken)', marginBottom: 6, opacity: 1 - i * 0.2 }} />)}</div>
      ) : subView === 'calendario' ? (
        <AgregadoCampanhasGantt itens={ganttItens} year={year} onItemClick={openCampanha} />
      ) : (
        <AgregadoCalendarView itens={editorialItens} onItemClick={it => onSelectPlano(it.plano_id)} />
      )}
    </div>
  );
};

// ─── MktPlanoComunicacaoScreen ────────────────────────────────────────────────

const MktPlanoComunicacaoScreen = () => {
  const [selectedId, setSelectedId] = React.useState(null);
  const [brandSlug, setBrandSlug] = React.useState('todas');
  const [brands, setBrands] = React.useState([]);
  const [kpi, setKpi] = React.useState({ total: 0, producao: 0 });
  const [zoneReady, setZoneReady] = React.useState(false);
  window.useMktZoneLoading(!zoneReady);

  React.useEffect(() => {
    let stop = false;
    Promise.all([
      campApiCall('/api/marketing/brands').then(b => { if (!stop) setBrands((b || []).filter(x => x.slug !== 'todas')); }).catch(() => {}),
      campApiCall('/api/marketing/campanhas-gantt-agregado?year=2026&pipeline=0')
        .then(d => {
          if (stop) return;
          const itens = d.itens || [];
          setKpi({ total: new Set(itens.map(i => i.campanha_id)).size, producao: new Set(itens.filter(i => i.campanha_status === 'em_producao').map(i => i.campanha_id)).size });
        }).catch(() => {}),
    ]).finally(() => { if (!stop) setZoneReady(true); });
    return () => { stop = true; };
  }, []);

  if (selectedId) return <PlanoDetail planoId={selectedId} onBack={() => setSelectedId(null)} />;

  const brandTabs = [{ slug: 'todas', name: 'Todas' }, ...brands];
  const pct = kpi.total ? Math.round(kpi.producao / kpi.total * 100) : 0;

  return (
    <div data-theme="light" style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg)' }}>
      <div style={{ background: 'var(--bg-elev)', borderBottom: '1px solid var(--border)', padding: '20px 40px 0', flexShrink: 0 }}>
        <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.07em', color: 'var(--text-muted)', textTransform: 'uppercase', marginBottom: 6, fontFamily: 'var(--font-mono)' }}>
          MARKETING · PLANO DE COMUNICAÇÃO
        </div>
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16 }}>
          <div>
            <h1 style={{ margin: 0, fontSize: 21, fontWeight: 700, color: 'var(--text)', fontFamily: 'var(--font-display)', letterSpacing: '-0.01em', lineHeight: 1.2 }}>
              Plano de Comunicação
            </h1>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 6, flexWrap: 'wrap' }}>
              <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>
                {kpi.total} campanha{kpi.total !== 1 ? 's' : ''} em calendário · {kpi.producao} em produção
              </span>
              {kpi.total > 0 && (
                <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                  <div style={{ width: 60, height: 4, borderRadius: 99, background: 'var(--border)', overflow: 'hidden' }}>
                    <div style={{ width: `${pct}%`, height: '100%', borderRadius: 99, background: 'var(--ai-500)' }} />
                  </div>
                  <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>{pct}% em produção</span>
                </div>
              )}
            </div>
          </div>
        </div>
        <div style={{ height: 1, background: 'var(--border)', margin: '16px -40px 0' }} />
        <div style={{ display: 'flex', gap: 0, overflowX: 'auto' }}>
          {brandTabs.map(b => {
            const active = b.slug === brandSlug;
            return (
              <button key={b.slug} onClick={() => setBrandSlug(b.slug)}
                style={{
                  background: 'none', border: 'none', outline: 'none',
                  borderBottom: `2px solid ${active ? 'var(--ai-500)' : 'transparent'}`,
                  color: active ? 'var(--text)' : 'var(--text-muted)',
                  fontSize: 13, fontWeight: active ? 600 : 500,
                  fontFamily: 'var(--font-display)', letterSpacing: '.01em',
                  padding: '10px 18px 12px', cursor: 'pointer', whiteSpace: 'nowrap',
                }}>
                {b.name}
              </button>
            );
          })}
        </div>
      </div>
      <div className="scrollbar" style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '28px 40px 48px', background: 'var(--bg)' }}>
        {brandSlug === 'todas'
          ? <TodasMarcasView onSelectPlano={setSelectedId} />
          : <PlanoList onSelect={setSelectedId} brandSlug={brandSlug} brands={brands} />}
      </div>
    </div>
  );
};

window.MktPlanoComunicacaoScreen = MktPlanoComunicacaoScreen;
