/* 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>
);

// ─── 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 }) => {
  const [planos, setPlanos] = React.useState([]);
  const [brands, setBrands] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [showCreate, setShowCreate] = React.useState(false);
  const [filterBrand, setFilterBrand] = React.useState('');
  const [filterYear, setFilterYear] = React.useState('');

  React.useEffect(() => {
    Promise.all([
      fetch('/api/marketing/plano').then(r => r.json()),
      fetch('/api/marketing/brands').then(r => r.json()),
    ]).then(([p, b]) => { setPlanos(p); setBrands(b); }).finally(() => setLoading(false));
  }, []);

  const filtered = planos.filter(p => {
    if (filterBrand && String(p.brand_id) !== filterBrand) return false;
    if (filterYear && String(p.year) !== filterYear) return false;
    return true;
  });

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      {/* Toolbar */}
      <div style={{ display: 'flex', gap: 7, alignItems: 'center' }}>
        <PSelect value={filterBrand} onChange={setFilterBrand} options={brands.map(b => [String(b.id), b.name])} placeholder="Todas as marcas" />
        <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={brands} onCreated={id => { setShowCreate(false); onSelect(id); }} onClose={() => setShowCreate(false)} />}
    </div>
  );
};

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

const MktPlanoComunicacaoScreen = () => {
  const [selectedId, setSelectedId] = React.useState(null);

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

  return (
    <div className="scrollbar" style={{ height: '100%', overflowY: 'auto' }}>
      <div style={{ padding: '28px 32px 0', marginBottom: 20 }}>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em' }}>MARKETING · PLANO DE COMUNICAÇÃO</div>
        <h1 className="font-display" style={{ margin: '6px 0 4px', fontSize: 26, fontWeight: 600, letterSpacing: '-0.015em' }}>Plano de Comunicação</h1>
        <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>Calendários editoriais trimestrais · gerados por AI · por marca</div>
      </div>
      <div style={{ padding: '0 32px 48px', maxWidth: 740 }}>
        <PlanoList onSelect={setSelectedId} />
      </div>
    </div>
  );
};

window.MktPlanoComunicacaoScreen = MktPlanoComunicacaoScreen;
