/* screen_marketing_activacao.jsx
   Marketing · Activação — Aprovação, agendamento e publicação de peças.
   Views: Dashboard · Fila · Calendário · Histórico · Config
   Expõe window.MktActivacaoScreen.
*/

// ── Approver scope ─────────────────────────────────────────────────────────────
const _APPROVER_SCOPE = {
  'fabio.costa@digidelta.pt':  'all',
  'rui.leitao@digidelta.pt':   'all',
  'bruno@netscreen.pt':        'netscreen_only',
  'bruno.rosa@digidelta.pt':   'netscreen_only',
  'armando@digidelta.pt':      'all_except_netscreen',
  'armando.mota@digidelta.pt': 'all_except_netscreen',
};

function getApproverScope(email) {
  if (!email) return 'all';
  return _APPROVER_SCOPE[email.toLowerCase()] || 'all';
}

function canApprovePeca(email, peca) {
  const scope = getApproverScope(email);
  if (scope === 'all') return true;
  if (scope === 'netscreen_only') return peca.marca_slug === 'netscreen';
  if (scope === 'all_except_netscreen') return peca.marca_slug !== 'netscreen';
  return true;
}

// ── Current user ───────────────────────────────────────────────────────────────
function getCurrentUser() {
  const params = new URLSearchParams(window.location.search);
  if (params.get('dev') === 'costa') {
    return { email: 'fabio.costa@digidelta.pt', nome_apresentar: 'Fábio Costa' };
  }
  return window.currentUser || { email: 'fabio.costa@digidelta.pt', nome_apresentar: 'Fábio Costa' };
}

// ── Status config ──────────────────────────────────────────────────────────────
const ACT_STATUS = {
  pending:         { label: 'Pendente',    color: '#F59E0B', bg: 'rgba(245,158,11,0.12)' },
  ready_review:    { label: 'Para rever',  color: '#3859D0', bg: 'rgba(56,89,208,0.12)' },
  approved:        { label: 'Aprovada',    color: '#10B981', bg: 'rgba(16,185,129,0.12)' },
  scheduled:       { label: 'Agendada',    color: '#3859D0', bg: 'rgba(56,89,208,0.12)' },
  publishing:      { label: 'A publicar',  color: '#F59E0B', bg: 'rgba(245,158,11,0.12)', pulse: true },
  published:       { label: 'Publicada',   color: '#10B981', bg: 'rgba(16,185,129,0.12)' },
  failed_publish:  { label: 'Falhou',      color: '#EF4444', bg: 'rgba(239,68,68,0.12)' },
  cancelled:       { label: 'Cancelada',   color: '#9CA3AF', bg: 'rgba(156,163,175,0.12)' },
  paused:          { label: 'Pausada',     color: '#9CA3AF', bg: 'rgba(156,163,175,0.12)' },
};

function ActStatusBadge({ status }) {
  const cfg = ACT_STATUS[status] || ACT_STATUS.pending;
  return (
    <span style={{
      display: 'inline-block', fontSize: 10.5, fontWeight: 600,
      padding: '2px 8px', borderRadius: 99,
      color: cfg.color, background: cfg.bg,
      fontFamily: 'var(--font-mono, monospace)',
      animation: cfg.pulse ? 'pulse 1.5s ease-in-out infinite' : 'none',
      whiteSpace: 'nowrap',
    }}>
      {cfg.label}
    </span>
  );
}

// ── Cores de marca ─────────────────────────────────────────────────────────────
const _AC = {
  mimaki: '#e60012', biond: '#00a86b', decal: '#f59e0b',
  alldecor: '#ec4899', sensek: '#8B2DE8', netscreen: '#F97316', digidelta: '#3859D0',
};
const _actBrandColor = (s) => _AC[s] || '#3859D0';

// ── Canal label ───────────────────────────────────────────────────────────────
const CANAL_LABELS = {
  meta: 'Meta', meta_ads: 'Meta Ads', instagram: 'Instagram', facebook: 'Facebook',
  linkedin: 'LinkedIn', linkedin_ads: 'LinkedIn Ads',
  email: 'Email', muppi_led: 'Muppi LED',
  novastar: 'NovaStar', branddigital: 'Branddigital', dooh: 'DOOH',
};
const canalLabel = (c) => CANAL_LABELS[c] || c;

// ── API helpers ────────────────────────────────────────────────────────────────
async function actFetch(url, opts = {}) {
  try {
    const res = await fetch(url, { headers: { 'Content-Type': 'application/json' }, ...opts });
    if (!res.ok) { let b = {}; try { b = await res.json(); } catch {} throw new Error(b.error || `HTTP ${res.status}`); }
    return res.json();
  } catch (e) {
    throw e;
  }
}

const ActAPI = {
  dashboard: (email) => actFetch(`/api/marketing/activacao/dashboard?approver_email=${encodeURIComponent(email)}`),
  fila: (params) => actFetch(`/api/marketing/activacao/fila?${new URLSearchParams(params)}`),
  aprovar: (id, actor_email, actor_name) => actFetch(`/api/marketing/activacao/peca/${id}/aprovar`, { method: 'POST', body: JSON.stringify({ actor_email, actor_name }) }),
  rejeitar: (id, actor_email, actor_name, reason) => actFetch(`/api/marketing/activacao/peca/${id}/rejeitar`, { method: 'POST', body: JSON.stringify({ actor_email, actor_name, reason }) }),
  agendar: (id, scheduled_for, actor_email) => actFetch(`/api/marketing/activacao/peca/${id}/agendar`, { method: 'POST', body: JSON.stringify({ scheduled_for, actor_email }) }),
  reagendar: (id, scheduled_for, actor_email) => actFetch(`/api/marketing/activacao/peca/${id}/reagendar`, { method: 'POST', body: JSON.stringify({ scheduled_for, actor_email }) }),
  cancelar: (id, actor_email, reason) => actFetch(`/api/marketing/activacao/peca/${id}/cancelar`, { method: 'POST', body: JSON.stringify({ actor_email, reason }) }),
  aprovarBulk: (peca_ids, actor_email, actor_name) => actFetch('/api/marketing/activacao/aprovar-bulk', { method: 'POST', body: JSON.stringify({ peca_ids, actor_email, actor_name }) }),
  calendario: (params) => actFetch(`/api/marketing/activacao/calendario?${new URLSearchParams(params)}`),
  historico: (params) => actFetch(`/api/marketing/activacao/historico?${new URLSearchParams(params)}`),
  logs: (peca_id) => actFetch(`/api/marketing/activacao/logs/${peca_id}`),
  retry: (id, actor_email) => actFetch(`/api/marketing/activacao/peca/${id}/retry`, { method: 'POST', body: JSON.stringify({ actor_email }) }),
};

// ── Formatters ─────────────────────────────────────────────────────────────────
function fmtDate(iso) {
  if (!iso) return '—';
  const d = new Date(iso);
  if (isNaN(d)) return '—';
  return d.toLocaleDateString('pt-PT', { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' });
}
function fmtDateShort(iso) {
  if (!iso) return '—';
  const d = new Date(iso);
  if (isNaN(d)) return '—';
  return d.toLocaleDateString('pt-PT', { day: '2-digit', month: 'short' });
}
function fmtRelative(iso) {
  if (!iso) return '';
  const diff = Date.now() - new Date(iso).getTime();
  const mins = Math.floor(diff / 60000);
  if (mins < 2) return 'agora';
  if (mins < 60) return `há ${mins}m`;
  const h = Math.floor(mins / 60);
  if (h < 24) return `há ${h}h`;
  const d = Math.floor(h / 24);
  return `há ${d}d`;
}

// ── Dropdown (namespace único) ─────────────────────────────────────────────────
const ActivacaoDropdown = ({ label, value, options, onChange, disabled, minWidth = 160 }) => {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, [open]);
  const current = options.find(o => o.value === value) || options[0];
  return (
    <div ref={ref} style={{ position: 'relative', display: 'inline-block' }}>
      <button onClick={() => !disabled && setOpen(v => !v)} disabled={disabled} style={{
        background: 'var(--bg-elev)', color: disabled ? 'var(--text-dim)' : 'var(--text)',
        border: '1px solid var(--border)', borderRadius: 6,
        padding: '6px 10px', fontSize: 11.5,
        display: 'inline-flex', alignItems: 'center', gap: 8,
        cursor: disabled ? 'not-allowed' : 'pointer', opacity: disabled ? 0.55 : 1,
        fontFamily: 'inherit', whiteSpace: 'nowrap',
      }}>
        <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: 120,
          background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 6,
          boxShadow: '0 8px 24px rgba(17,41,84,0.12)', minWidth, padding: 4, maxHeight: 260, 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', whiteSpace: 'nowrap',
            }}>{o.label}</button>
          ))}
        </div>
      )}
    </div>
  );
};

// ── Empty state ────────────────────────────────────────────────────────────────
const ActEmptyState = ({ icon, title, sub }) => (
  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '56px 24px', gap: 12, color: 'var(--text-muted)' }}>
    <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{ opacity: 0.35 }}>
      {icon === 'inbox' && <><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 7V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v2"/><line x1="12" y1="12" x2="12" y2="16"/><line x1="10" y1="14" x2="14" y2="14"/></>}
      {icon === 'calendar' && <><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></>}
      {icon === 'history' && <><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 .49-4.5"/></>}
      {icon === 'settings' && <><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></>}
      {!icon && <><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></>}
    </svg>
    <div style={{ fontWeight: 600, fontSize: 14, color: 'var(--text)' }}>{title || 'Sem dados'}</div>
    {sub && <div style={{ fontSize: 12, color: 'var(--text-muted)', textAlign: 'center', maxWidth: 320, lineHeight: 1.6 }}>{sub}</div>}
  </div>
);

// ── Spinner ────────────────────────────────────────────────────────────────────
const ActSpinner = () => (
  <div style={{ display: 'flex', justifyContent: 'center', padding: '48px 0' }}>
    <div style={{ width: 28, height: 28, border: '2.5px solid var(--border)', borderTopColor: 'var(--brand-primary, #3859D0)', borderRadius: '50%', animation: 'spin 0.75s linear infinite' }}/>
  </div>
);

// ═══════════════════════════════════════════════════════════════════════════════
// MOCK DATA (fallback when API returns 404 or error)
// ═══════════════════════════════════════════════════════════════════════════════
const MOCK_PECAS = [
  { id: 'p1', marca_slug: 'mimaki', canal_pai: 'instagram', content_type: 'IG Story', headline: 'TS300-1600: pedido de demonstração', status: 'ready_review', scheduled_for: new Date(Date.now() + 3 * 3600000).toISOString(), created_at: new Date(Date.now() - 7200000).toISOString(), thumbnail_url: null },
  { id: 'p2', marca_slug: 'mimaki', canal_pai: 'facebook', content_type: 'FB Post', headline: 'Impressão têxtil de nova geração', status: 'ready_review', scheduled_for: new Date(Date.now() + 86400000).toISOString(), created_at: new Date(Date.now() - 3600000).toISOString(), thumbnail_url: null },
  { id: 'p3', marca_slug: 'biond', canal_pai: 'linkedin', content_type: 'Post', headline: 'BIOND Films em parceria com produtoras europeias', status: 'scheduled', scheduled_for: new Date(Date.now() + 2 * 86400000).toISOString(), created_at: new Date(Date.now() - 86400000).toISOString(), thumbnail_url: null },
  { id: 'p4', marca_slug: 'decal', canal_pai: 'email', content_type: 'Newsletter', headline: 'Cast vinyl: promoção de Julho', status: 'approved', scheduled_for: new Date(Date.now() + 4 * 86400000).toISOString(), created_at: new Date(Date.now() - 2 * 86400000).toISOString(), thumbnail_url: null },
  { id: 'p5', marca_slug: 'netscreen', canal_pai: 'novastar', content_type: 'LED Content', headline: 'NetScreen Q3 2026 campaign', status: 'failed_publish', scheduled_for: new Date(Date.now() - 3600000).toISOString(), created_at: new Date(Date.now() - 5 * 86400000).toISOString(), thumbnail_url: null },
  { id: 'p6', marca_slug: 'mimaki', canal_pai: 'meta_ads', content_type: 'Ad 1:1', headline: 'TS300: ROI em 18 meses', status: 'published', scheduled_for: new Date(Date.now() - 86400000).toISOString(), published_url: 'https://facebook.com/ads/123', created_at: new Date(Date.now() - 7 * 86400000).toISOString(), thumbnail_url: null },
];

const MOCK_DASHBOARD = {
  kpis: { pendentes: 2, agendadas: 1, hoje: 1, falhou: 1 },
  a_precisar_acao: MOCK_PECAS.filter(p => p.status === 'ready_review'),
  proximas_7d: {
    instagram: ['', 'p1', '', '', '', '', ''],
    facebook:  ['', '', 'p2', '', '', '', ''],
    linkedin:  ['', '', '', 'p3', '', '', ''],
    email:     ['', '', '', '', 'p4', '', ''],
  },
};

const MOCK_CONTAS = [
  { marca_slug: 'mimaki', canal: 'meta_fb',   status: 'ok',      expira_em: 32, account_name: 'Mimaki PT FB' },
  { marca_slug: 'mimaki', canal: 'meta_ig',   status: 'ok',      expira_em: 32, account_name: 'Mimaki PT IG' },
  { marca_slug: 'mimaki', canal: 'linkedin',  status: 'ok',      expira_em: 58, account_name: 'Mimaki PT LI' },
  { marca_slug: 'mimaki', canal: 'email',     status: 'ok',      expira_em: null, account_name: 'Brevo SMTP' },
  { marca_slug: 'mimaki', canal: 'muppi_led', status: 'ok',      expira_em: null, account_name: 'Muppi 3 panels' },
  { marca_slug: 'biond',  canal: 'meta_fb',   status: 'ok',      expira_em: 32, account_name: 'BIOND FB' },
  { marca_slug: 'biond',  canal: 'meta_ig',   status: 'ok',      expira_em: 32, account_name: 'BIOND IG' },
  { marca_slug: 'biond',  canal: 'linkedin',  status: 'warning', expira_em: 12, account_name: 'BIOND LI' },
  { marca_slug: 'biond',  canal: 'email',     status: 'ok',      expira_em: null, account_name: 'Brevo SMTP' },
  { marca_slug: 'decal',  canal: 'meta_fb',   status: 'ok',      expira_em: 32, account_name: 'Decal FB' },
  { marca_slug: 'decal',  canal: 'meta_ig',   status: 'ok',      expira_em: 32, account_name: 'Decal IG' },
  { marca_slug: 'decal',  canal: 'linkedin',  status: 'ok',      expira_em: 58, account_name: 'Decal LI' },
  { marca_slug: 'decal',  canal: 'email',     status: 'ok',      expira_em: null, account_name: 'Brevo SMTP' },
  { marca_slug: 'netscreen', canal: 'novastar',    status: 'ok', expira_em: null, account_name: 'NovaStar CMS' },
  { marca_slug: 'netscreen', canal: 'branddigital', status: 'ok', expira_em: null, account_name: 'Branddigital DOOH' },
];

// ═══════════════════════════════════════════════════════════════════════════════
// HEADER
// ═══════════════════════════════════════════════════════════════════════════════
const ActivacaoHeader = ({ user }) => {
  const hour = new Date().getHours();
  const saudacao = hour < 12 ? 'Bom dia' : hour < 19 ? 'Boa tarde' : 'Boa noite';
  const first = (user?.nome_apresentar || user?.nome || '').split(' ')[0] || '';
  return (
    <div style={{ padding: '28px 32px 0', flexShrink: 0 }}>
      <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em' }}>
        MARKETING · ACTIVAÇÃO
      </div>
      <h1 className="font-display" style={{ margin: '6px 0 4px', fontSize: 26, fontWeight: 600, letterSpacing: '-0.015em', color: 'var(--text)' }}>
        Activação
      </h1>
      <div style={{ fontSize: 13, color: 'var(--text-muted)' }}>
        {saudacao}{first ? `, ${first}` : ''}. Aprovação · agendamento · publicação automática.
      </div>
    </div>
  );
};

// ═══════════════════════════════════════════════════════════════════════════════
// NAV TABS
// ═══════════════════════════════════════════════════════════════════════════════
const _NAV_TABS = [
  { id: 'dashboard',  label: 'Dashboard' },
  { id: 'fila',       label: 'Fila' },
  { id: 'calendario', label: 'Calendário' },
  { id: 'historico',  label: 'Histórico' },
  { id: 'config',     label: 'Config' },
];

const ActivacaoNav = ({ view, onChange }) => (
  <div style={{ padding: '16px 32px 0', borderBottom: '1px solid var(--border)', display: 'flex', gap: 0, flexShrink: 0 }}>
    {_NAV_TABS.map(t => {
      const active = view === t.id;
      return (
        <button key={t.id} onClick={() => onChange(t.id)} style={{
          background: 'transparent', border: 'none', cursor: 'pointer',
          padding: '8px 14px', fontSize: 13, fontWeight: active ? 600 : 500,
          color: active ? 'var(--brand-primary, #3859D0)' : 'var(--text-muted)',
          borderBottom: active ? '2px solid var(--brand-primary, #3859D0)' : '2px solid transparent',
          marginBottom: -1, transition: 'color .15s', fontFamily: 'var(--font-body)',
        }}>
          {t.label}
        </button>
      );
    })}
  </div>
);

// ═══════════════════════════════════════════════════════════════════════════════
// DASHBOARD VIEW
// ═══════════════════════════════════════════════════════════════════════════════

const KpiStrip = ({ kpis, onDrillDown }) => {
  const cards = [
    { id: 'pendentes', label: 'Pendentes', value: kpis?.pendentes ?? 0, color: '#F59E0B' },
    { id: 'agendadas', label: 'Agendadas', value: kpis?.agendadas ?? 0, color: '#3859D0' },
    { id: 'hoje',      label: 'Publicam hoje', value: kpis?.hoje ?? 0, color: '#10B981' },
    { id: 'falhou',    label: 'Falharam', value: kpis?.falhou ?? 0, color: '#EF4444' },
  ];
  return (
    <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
      {cards.map(c => (
        <div key={c.id} onClick={() => onDrillDown && onDrillDown(c.id)} style={{
          flex: '1 1 140px', minWidth: 120,
          background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 10,
          padding: '14px 18px', cursor: 'pointer', transition: 'border-color .15s',
        }}
          onMouseEnter={e => e.currentTarget.style.borderColor = c.color}
          onMouseLeave={e => e.currentTarget.style.borderColor = 'var(--border)'}
        >
          <div style={{ fontSize: 9.5, fontWeight: 600, letterSpacing: '0.10em', textTransform: 'uppercase', color: 'var(--text-muted)', fontFamily: 'var(--font-mono)', marginBottom: 4 }}>{c.label}</div>
          <div style={{ fontSize: 28, fontWeight: 700, color: c.color, fontFamily: 'var(--font-display)', lineHeight: 1 }}>{c.value}</div>
        </div>
      ))}
    </div>
  );
};

const AcaoUrgenteList = ({ pecas, user, onAprovar, onExpandFila }) => {
  if (!pecas || pecas.length === 0) {
    return (
      <div style={{ background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 10, padding: '20px 24px' }}>
        <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-muted)', fontFamily: 'var(--font-mono)', letterSpacing: '0.07em', marginBottom: 12 }}>A PRECISAR DE TI</div>
        <ActEmptyState icon="inbox" title="Nenhuma peça pendente" sub="Tudo tratado por agora." />
      </div>
    );
  }
  return (
    <div style={{ background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 10, padding: '20px 24px' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
        <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-muted)', fontFamily: 'var(--font-mono)', letterSpacing: '0.07em' }}>A PRECISAR DE TI</div>
        {pecas.length > 3 && (
          <button className="btn btn-xs" onClick={onExpandFila} style={{ fontFamily: 'var(--font-body)' }}>
            Ver todas ({pecas.length})
          </button>
        )}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {pecas.slice(0, 5).map(p => (
          <div key={p.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px', background: 'var(--bg-app)', border: '1px solid var(--border)', borderRadius: 8 }}>
            <div style={{ width: 6, height: 6, borderRadius: '50%', background: _actBrandColor(p.marca_slug), flexShrink: 0 }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.headline || '—'}</div>
              <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>
                {p.marca_slug} · {canalLabel(p.canal_pai)} · {fmtRelative(p.created_at)}
              </div>
            </div>
            <ActStatusBadge status={p.status} />
            {canApprovePeca(user?.email, p) && p.status === 'ready_review' && (
              <button className="btn-ai" style={{ padding: '4px 12px', fontSize: 11.5, fontFamily: 'var(--font-body)', borderRadius: 6, cursor: 'pointer' }}
                onClick={() => onAprovar(p)}>
                Aprovar
              </button>
            )}
          </div>
        ))}
      </div>
    </div>
  );
};

const Proximos7DiasGrid = ({ proximas7d }) => {
  const today = new Date();
  const days = Array.from({ length: 7 }, (_, i) => {
    const d = new Date(today);
    d.setDate(d.getDate() + i);
    return d;
  });
  const canais = Object.keys(proximas7d || {});
  if (!canais.length) {
    return (
      <div style={{ background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 10, padding: '20px 24px' }}>
        <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-muted)', fontFamily: 'var(--font-mono)', letterSpacing: '0.07em', marginBottom: 12 }}>PRÓXIMOS 7 DIAS</div>
        <ActEmptyState icon="calendar" title="Sem publicações agendadas" sub="Aprova e agenda peças na Fila." />
      </div>
    );
  }
  return (
    <div style={{ background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 10, padding: '20px 24px', overflowX: 'auto' }}>
      <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-muted)', fontFamily: 'var(--font-mono)', letterSpacing: '0.07em', marginBottom: 14 }}>PRÓXIMOS 7 DIAS</div>
      <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 600 }}>
        <thead>
          <tr>
            <th style={{ width: 100, textAlign: 'left', fontSize: 11, color: 'var(--text-dim)', fontWeight: 500, padding: '0 8px 8px 0', fontFamily: 'var(--font-mono)' }}>Canal</th>
            {days.map((d, i) => (
              <th key={i} style={{ textAlign: 'center', fontSize: 10.5, color: i === 0 ? 'var(--brand-primary, #3859D0)' : 'var(--text-muted)', fontWeight: i === 0 ? 700 : 500, padding: '0 4px 8px', minWidth: 64, fontFamily: 'var(--font-mono)' }}>
                {d.toLocaleDateString('pt-PT', { weekday: 'short', day: 'numeric' })}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {canais.map(canal => (
            <tr key={canal}>
              <td style={{ fontSize: 11.5, color: 'var(--text-muted)', padding: '5px 8px 5px 0', whiteSpace: 'nowrap', fontWeight: 500 }}>{canalLabel(canal)}</td>
              {days.map((_, di) => {
                const val = proximas7d[canal]?.[di];
                const hasItem = val && val !== '';
                return (
                  <td key={di} style={{ textAlign: 'center', padding: '4px' }}>
                    {hasItem ? (
                      <div style={{ width: 10, height: 10, borderRadius: '50%', background: 'var(--brand-primary, #3859D0)', margin: '0 auto', opacity: 0.75 }} />
                    ) : (
                      <div style={{ width: 10, height: 10, borderRadius: '50%', background: 'var(--border)', margin: '0 auto', opacity: 0.3 }} />
                    )}
                  </td>
                );
              })}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

const DashboardView = ({ user, onNavigate }) => {
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [confirming, setConfirming] = React.useState(null);

  const load = React.useCallback(async () => {
    try {
      const d = await ActAPI.dashboard(user.email);
      setData(d);
    } catch {
      setData(MOCK_DASHBOARD);
    } finally {
      setLoading(false);
    }
  }, [user.email]);

  React.useEffect(() => {
    load();
    const t = setInterval(load, 30000);
    return () => clearInterval(t);
  }, [load]);

  const handleAprovar = async (peca) => {
    if (!window.confirm(`Aprovar "${peca.headline}"?`)) return;
    try {
      await ActAPI.aprovar(peca.id, user.email, user.nome_apresentar || user.nome || '');
      load();
    } catch (e) { alert(`Erro: ${e.message}`); }
  };

  if (loading) return <ActSpinner />;

  return (
    <div style={{ padding: '24px 32px', display: 'flex', flexDirection: 'column', gap: 20 }}>
      <KpiStrip kpis={data?.kpis} onDrillDown={(id) => onNavigate('fila')} />
      <AcaoUrgenteList pecas={data?.a_precisar_acao} user={user} onAprovar={handleAprovar} onExpandFila={() => onNavigate('fila')} />
      <Proximos7DiasGrid proximas7d={data?.proximas_7d} />
    </div>
  );
};

// ═══════════════════════════════════════════════════════════════════════════════
// FILA VIEW
// ═══════════════════════════════════════════════════════════════════════════════

const PecaLogDrawer = ({ peca, onClose, user }) => {
  const [logs, setLogs] = React.useState(null);
  const [agendarInput, setAgendarInput] = React.useState('');
  const [rejeitarReason, setRejeitarReason] = React.useState('');
  const [view, setView] = React.useState('detail'); // 'detail' | 'agendar' | 'rejeitar'
  const [saving, setSaving] = React.useState(false);
  const [savedLabel, setSavedLabel] = React.useState('');

  React.useEffect(() => {
    if (!peca) return;
    ActAPI.logs(peca.id).then(setLogs).catch(() => setLogs([]));
    // Pre-fill scheduler
    if (peca.scheduled_for) setAgendarInput(peca.scheduled_for.slice(0, 16));
  }, [peca?.id]);

  if (!peca) return null;

  const canApprove = canApprovePeca(user?.email, peca);

  const doAprovar = async () => {
    setSaving(true);
    try {
      await ActAPI.aprovar(peca.id, user.email, user.nome_apresentar || '');
      setSavedLabel('Aprovada');
      setTimeout(() => { setSavedLabel(''); onClose(true); }, 1200);
    } catch (e) { alert(`Erro: ${e.message}`); setSaving(false); }
  };

  const doAgendar = async () => {
    if (!agendarInput) return;
    setSaving(true);
    try {
      const fn = peca.status === 'scheduled' ? ActAPI.reagendar : ActAPI.agendar;
      await fn(peca.id, new Date(agendarInput).toISOString(), user.email);
      setSavedLabel('Agendada');
      setTimeout(() => { setSavedLabel(''); onClose(true); }, 1200);
    } catch (e) { alert(`Erro: ${e.message}`); setSaving(false); }
  };

  const doRejeitar = async () => {
    if (!rejeitarReason.trim()) { alert('Indica o motivo da rejeição.'); return; }
    setSaving(true);
    try {
      await ActAPI.rejeitar(peca.id, user.email, user.nome_apresentar || '', rejeitarReason);
      setSavedLabel('Rejeitada');
      setTimeout(() => { setSavedLabel(''); onClose(true); }, 1200);
    } catch (e) { alert(`Erro: ${e.message}`); setSaving(false); }
  };

  const doCancelar = async () => {
    if (!window.confirm('Cancelar esta peça?')) return;
    setSaving(true);
    try {
      await ActAPI.cancelar(peca.id, user.email, 'Cancelado manualmente');
      onClose(true);
    } catch (e) { alert(`Erro: ${e.message}`); setSaving(false); }
  };

  const doRetry = async () => {
    setSaving(true);
    try {
      await ActAPI.retry(peca.id, user.email);
      setSavedLabel('Re-tentativa iniciada');
      setTimeout(() => { setSavedLabel(''); onClose(true); }, 1200);
    } catch (e) { alert(`Erro: ${e.message}`); setSaving(false); }
  };

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 200, display: 'flex', alignItems: 'flex-start', justifyContent: 'flex-end', background: 'rgba(10,16,30,0.45)' }}
      onClick={e => { if (e.target === e.currentTarget) onClose(); }}>
      <div style={{ width: 420, height: '100%', background: 'var(--bg-app)', boxShadow: '-8px 0 32px rgba(17,41,84,0.14)', display: 'flex', flexDirection: 'column', overflowY: 'auto' }}>
        {/* Header */}
        <div style={{ padding: '20px 24px 16px', borderBottom: '1px solid var(--border)', flexShrink: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
            <div style={{ fontSize: 10, fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', color: 'var(--text-dim)', textTransform: 'uppercase' }}>Detalhe da peça</div>
            <button onClick={() => onClose()} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-muted)', fontSize: 18, lineHeight: 1 }}>×</button>
          </div>
          <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', fontFamily: 'var(--font-display)', marginBottom: 6 }}>{peca.headline || '—'}</div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
            <span style={{ fontSize: 11.5, color: _actBrandColor(peca.marca_slug), fontWeight: 600 }}>{peca.marca_slug}</span>
            <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>{canalLabel(peca.canal_pai)}</span>
            <ActStatusBadge status={peca.status} />
          </div>
        </div>

        {/* Info */}
        <div style={{ padding: '16px 24px', borderBottom: '1px solid var(--border)', flexShrink: 0 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            {[
              { label: 'Tipo', val: peca.content_type },
              { label: 'Agendado', val: fmtDate(peca.scheduled_for) },
              { label: 'Criado', val: fmtDate(peca.created_at) },
              { label: 'Aprovado por', val: peca.approved_by_name || '—' },
              { label: 'URL publicado', val: peca.published_url ? 'Ver link' : '—', href: peca.published_url },
            ].map((row, i) => (
              <div key={i}>
                <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em', marginBottom: 2 }}>{row.label}</div>
                {row.href
                  ? <a href={row.href} target="_blank" rel="noopener noreferrer" style={{ fontSize: 12, color: 'var(--brand-primary)', fontWeight: 500 }}>{row.val}</a>
                  : <div style={{ fontSize: 12, color: 'var(--text)', fontWeight: 500 }}>{row.val || '—'}</div>
                }
              </div>
            ))}
          </div>
        </div>

        {/* Tabs actions */}
        <div style={{ padding: '12px 24px', display: 'flex', gap: 6, borderBottom: '1px solid var(--border)', flexShrink: 0, flexWrap: 'wrap' }}>
          {canApprove && peca.status === 'ready_review' && (
            <button className="btn-ai" style={{ padding: '6px 14px', fontSize: 12, borderRadius: 7, cursor: 'pointer', fontFamily: 'var(--font-body)' }}
              disabled={saving} onClick={doAprovar}>
              {savedLabel === 'Aprovada' ? 'Aprovada' : 'Aprovar'}
            </button>
          )}
          <button className="btn" style={{ padding: '6px 12px', fontSize: 12, borderRadius: 7, cursor: 'pointer', fontFamily: 'var(--font-body)' }}
            onClick={() => setView(view === 'agendar' ? 'detail' : 'agendar')}>
            {peca.status === 'scheduled' ? 'Reagendar' : 'Agendar'}
          </button>
          {peca.status === 'ready_review' && canApprove && (
            <button className="btn" style={{ padding: '6px 12px', fontSize: 12, borderRadius: 7, cursor: 'pointer', fontFamily: 'var(--font-body)' }}
              onClick={() => setView(view === 'rejeitar' ? 'detail' : 'rejeitar')}>
              Rejeitar
            </button>
          )}
          {peca.status === 'failed_publish' && (
            <button className="btn" style={{ padding: '6px 12px', fontSize: 12, borderRadius: 7, cursor: 'pointer', fontFamily: 'var(--font-body)' }}
              disabled={saving} onClick={doRetry}>
              Re-tentar
            </button>
          )}
          {!['published', 'cancelled'].includes(peca.status) && (
            <button className="btn" style={{ padding: '6px 12px', fontSize: 12, borderRadius: 7, cursor: 'pointer', color: 'var(--danger, #ef4444)', fontFamily: 'var(--font-body)' }}
              disabled={saving} onClick={doCancelar}>
              Cancelar
            </button>
          )}
        </div>

        {/* Inline panels */}
        {view === 'agendar' && (
          <div style={{ padding: '14px 24px', borderBottom: '1px solid var(--border)', background: 'var(--bg-sunken)' }}>
            <div style={{ fontSize: 12, fontWeight: 600, marginBottom: 8, color: 'var(--text)' }}>{peca.status === 'scheduled' ? 'Reagendar' : 'Agendar'}</div>
            <input type="datetime-local" value={agendarInput} onChange={e => setAgendarInput(e.target.value)}
              style={{ width: '100%', padding: '7px 10px', borderRadius: 7, border: '1px solid var(--border)', fontSize: 12.5, background: 'var(--bg-elev)', color: 'var(--text)', fontFamily: 'var(--font-body)', boxSizing: 'border-box', marginBottom: 10 }} />
            <button className="btn-ai" style={{ padding: '6px 14px', fontSize: 12, borderRadius: 7, cursor: 'pointer', fontFamily: 'var(--font-body)' }}
              disabled={saving || !agendarInput} onClick={doAgendar}>
              {savedLabel === 'Agendada' ? 'Agendada' : 'Confirmar'}
            </button>
          </div>
        )}
        {view === 'rejeitar' && (
          <div style={{ padding: '14px 24px', borderBottom: '1px solid var(--border)', background: 'var(--bg-sunken)' }}>
            <div style={{ fontSize: 12, fontWeight: 600, marginBottom: 8, color: 'var(--text)' }}>Motivo da rejeição</div>
            <textarea value={rejeitarReason} onChange={e => setRejeitarReason(e.target.value)} rows={3} placeholder="Descreve o problema..."
              style={{ width: '100%', padding: '7px 10px', borderRadius: 7, border: '1px solid var(--border)', fontSize: 12.5, background: 'var(--bg-elev)', color: 'var(--text)', fontFamily: 'var(--font-body)', boxSizing: 'border-box', resize: 'vertical', marginBottom: 10 }} />
            <button className="btn" style={{ padding: '6px 12px', fontSize: 12, borderRadius: 7, cursor: 'pointer', color: 'var(--danger)', fontFamily: 'var(--font-body)' }}
              disabled={saving} onClick={doRejeitar}>
              Confirmar rejeição
            </button>
          </div>
        )}

        {/* Audit log */}
        <div style={{ padding: '16px 24px', flex: 1 }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.07em', marginBottom: 10 }}>HISTÓRICO</div>
          {!logs ? (
            <ActSpinner />
          ) : logs.length === 0 ? (
            <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>Sem registos.</div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {logs.map((log, i) => (
                <div key={log.id || i} style={{ display: 'flex', gap: 10 }}>
                  <div style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--border)', marginTop: 5, flexShrink: 0 }} />
                  <div>
                    <div style={{ fontSize: 11.5, color: 'var(--text)', fontWeight: 500 }}>{log.event_type?.replace(/_/g, ' ')}</div>
                    <div style={{ fontSize: 10.5, color: 'var(--text-muted)' }}>
                      {log.actor_name || log.actor_role} · {fmtRelative(log.created_at)}
                    </div>
                    {log.payload?.reason && <div style={{ fontSize: 10.5, color: 'var(--danger)' }}>{log.payload.reason}</div>}
                    {log.payload?.error && <div style={{ fontSize: 10.5, color: 'var(--danger)' }}>{log.payload.error}</div>}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

const PecaCard = ({ peca, user, selected, onSelect, onAction, onExpand }) => {
  const brandColor = _actBrandColor(peca.marca_slug);
  const canApprove = canApprovePeca(user?.email, peca);
  return (
    <div style={{
      background: 'var(--bg-elev)', border: `1px solid ${selected ? 'var(--brand-primary, #3859D0)' : 'var(--border)'}`,
      borderRadius: 10, overflow: 'hidden', transition: 'border-color .15s',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px' }}>
        {/* Checkbox */}
        <input type="checkbox" checked={selected} onChange={e => onSelect(e.target.checked)}
          style={{ width: 15, height: 15, accentColor: 'var(--brand-primary)', cursor: 'pointer', flexShrink: 0 }} />
        {/* Thumb */}
        <div style={{ width: 72, height: 72, borderRadius: 8, background: 'var(--bg-sunken)', border: '1px solid var(--border)', flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden' }}>
          {peca.thumbnail_url
            ? <img src={peca.thumbnail_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
            : <div style={{ width: 32, height: 32, borderRadius: 6, background: brandColor, opacity: 0.25 }} />
          }
        </div>
        {/* Info */}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap', marginBottom: 3 }}>
            <span style={{ fontSize: 11.5, fontWeight: 700, color: brandColor }}>{peca.marca_slug}</span>
            <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>{canalLabel(peca.canal_pai)} · {peca.content_type}</span>
            {peca.scheduled_for && (
              <span style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>{fmtDateShort(peca.scheduled_for)}</span>
            )}
          </div>
          <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', marginBottom: 4 }}>
            {peca.headline || '—'}
          </div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <ActStatusBadge status={peca.status} />
            <span style={{ fontSize: 10.5, color: 'var(--text-dim)' }}>{fmtRelative(peca.created_at)}</span>
          </div>
        </div>
        {/* Actions */}
        <div style={{ display: 'flex', gap: 6, flexShrink: 0, flexWrap: 'wrap', justifyContent: 'flex-end' }}>
          {canApprove && peca.status === 'ready_review' && (
            <button className="btn-ai" style={{ padding: '5px 12px', fontSize: 11.5, borderRadius: 6, cursor: 'pointer', fontFamily: 'var(--font-body)' }}
              onClick={() => onAction('aprovar', peca)}>
              Aprovar
            </button>
          )}
          <button className="btn btn-xs" style={{ fontFamily: 'var(--font-body)' }} onClick={() => onExpand(peca)}>
            Detalhes
          </button>
          {peca.status === 'failed_publish' && (
            <button className="btn btn-xs" style={{ fontFamily: 'var(--font-body)' }} onClick={() => onAction('retry', peca)}>
              Re-tentar
            </button>
          )}
        </div>
      </div>
    </div>
  );
};

const FilaView = ({ user }) => {
  const [pecas, setPecas] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [selected, setSelected] = React.useState(new Set());
  const [expanded, setExpanded] = React.useState(null);
  const [bulkLoading, setBulkLoading] = React.useState(false);
  const [filters, setFilters] = React.useState({ brand: 'all', canal: 'all', status: 'all' });

  const load = React.useCallback(async () => {
    setLoading(true);
    try {
      const params = { approver_email: user.email };
      if (filters.brand !== 'all') params.brand = filters.brand;
      if (filters.canal !== 'all') params.canal = filters.canal;
      if (filters.status !== 'all') params.status = filters.status;
      const d = await ActAPI.fila(params);
      const items = d?.pecas || d || [];
      // client-side scope filter
      setPecas(items.filter(p => canApprovePeca(user.email, p)));
    } catch {
      setPecas(MOCK_PECAS.filter(p => canApprovePeca(user.email, p)));
    } finally {
      setLoading(false);
    }
  }, [user.email, filters]);

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

  const handleAction = async (action, peca) => {
    if (action === 'aprovar') {
      if (!window.confirm(`Aprovar "${peca.headline}"?`)) return;
      try {
        await ActAPI.aprovar(peca.id, user.email, user.nome_apresentar || '');
        load();
      } catch (e) { alert(`Erro: ${e.message}`); }
    }
    if (action === 'retry') {
      try {
        await ActAPI.retry(peca.id, user.email);
        load();
      } catch (e) { alert(`Erro: ${e.message}`); }
    }
  };

  const handleBulkApprove = async () => {
    if (!selected.size) return;
    if (!window.confirm(`Aprovar ${selected.size} peça(s)?`)) return;
    setBulkLoading(true);
    try {
      await ActAPI.aprovarBulk(Array.from(selected), user.email, user.nome_apresentar || '');
      setSelected(new Set());
      load();
    } catch (e) { alert(`Erro: ${e.message}`); }
    finally { setBulkLoading(false); }
  };

  const toggleSelect = (id, checked) => {
    setSelected(prev => {
      const n = new Set(prev);
      if (checked) n.add(id); else n.delete(id);
      return n;
    });
  };

  const selectAll = () => {
    const approvable = pecas.filter(p => p.status === 'ready_review');
    if (selected.size === approvable.length) setSelected(new Set());
    else setSelected(new Set(approvable.map(p => p.id)));
  };

  const BRAND_OPTS = [
    { value: 'all', label: 'Todas as marcas' },
    { value: 'mimaki', label: 'Mimaki' }, { value: 'biond', label: 'BIOND' },
    { value: 'decal', label: 'Decal' }, { value: 'netscreen', label: 'NetScreen' },
    { value: 'alldecor', label: 'AllDecor' }, { value: 'sensek', label: 'Sensek' },
  ];
  const CANAL_OPTS = [
    { value: 'all', label: 'Todos os canais' },
    { value: 'instagram', label: 'Instagram' }, { value: 'facebook', label: 'Facebook' },
    { value: 'linkedin', label: 'LinkedIn' }, { value: 'email', label: 'Email' },
    { value: 'meta_ads', label: 'Meta Ads' }, { value: 'muppi_led', label: 'Muppi LED' },
    { value: 'novastar', label: 'NovaStar' }, { value: 'branddigital', label: 'Branddigital' },
  ];
  const STATUS_OPTS = [
    { value: 'all', label: 'Todos os estados' },
    { value: 'ready_review', label: 'Para rever' }, { value: 'approved', label: 'Aprovadas' },
    { value: 'scheduled', label: 'Agendadas' }, { value: 'failed_publish', label: 'Falharam' },
    { value: 'cancelled', label: 'Canceladas' },
  ];

  const approvableSelected = pecas.filter(p => selected.has(p.id) && p.status === 'ready_review');

  return (
    <div style={{ padding: '24px 32px', display: 'flex', flexDirection: 'column', gap: 16 }}>
      {/* Filters bar */}
      <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
        <ActivacaoDropdown label="Marca" value={filters.brand} options={BRAND_OPTS} onChange={v => setFilters(f => ({ ...f, brand: v }))} />
        <ActivacaoDropdown label="Canal" value={filters.canal} options={CANAL_OPTS} onChange={v => setFilters(f => ({ ...f, canal: v }))} />
        <ActivacaoDropdown label="Estado" value={filters.status} options={STATUS_OPTS} onChange={v => setFilters(f => ({ ...f, status: v }))} />
        <button className="btn btn-xs" onClick={load} style={{ fontFamily: 'var(--font-body)' }}>Actualizar</button>
        <div style={{ marginLeft: 'auto', fontSize: 11.5, color: 'var(--text-muted)' }}>{pecas.length} peças</div>
      </div>

      {/* Bulk bar */}
      {selected.size > 0 && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 16px', background: 'color-mix(in oklch, var(--brand-primary, #3859D0) 8%, transparent)', border: '1px solid color-mix(in oklch, var(--brand-primary, #3859D0) 20%, transparent)', borderRadius: 8 }}>
          <span style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--text)' }}>{selected.size} seleccionadas</span>
          {approvableSelected.length > 0 && (
            <button className="btn-ai" disabled={bulkLoading} onClick={handleBulkApprove}
              style={{ padding: '5px 14px', fontSize: 12, borderRadius: 6, cursor: 'pointer', fontFamily: 'var(--font-body)' }}>
              {bulkLoading ? 'A processar...' : `Aprovar ${approvableSelected.length}`}
            </button>
          )}
          <button className="btn btn-xs" onClick={() => setSelected(new Set())} style={{ fontFamily: 'var(--font-body)' }}>Limpar</button>
        </div>
      )}

      {/* Select all */}
      {pecas.filter(p => p.status === 'ready_review').length > 0 && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <input type="checkbox" checked={selected.size > 0 && selected.size === pecas.filter(p => p.status === 'ready_review').length}
            onChange={selectAll} style={{ accentColor: 'var(--brand-primary)', cursor: 'pointer' }} />
          <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>Seleccionar todas as que podem ser aprovadas</span>
        </div>
      )}

      {/* List */}
      {loading ? <ActSpinner /> : pecas.length === 0 ? (
        <ActEmptyState icon="inbox" title="Fila vazia" sub="Não há peças visíveis para ti com estes filtros." />
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {pecas.map(p => (
            <PecaCard key={p.id} peca={p} user={user}
              selected={selected.has(p.id)}
              onSelect={checked => toggleSelect(p.id, checked)}
              onAction={handleAction}
              onExpand={peca => setExpanded(peca)}
            />
          ))}
        </div>
      )}

      {/* Detail drawer */}
      {expanded && (
        <PecaLogDrawer peca={expanded} user={user} onClose={(refresh) => { setExpanded(null); if (refresh) load(); }} />
      )}
    </div>
  );
};

// ═══════════════════════════════════════════════════════════════════════════════
// CALENDÁRIO VIEW
// ═══════════════════════════════════════════════════════════════════════════════

const CalendarioView = ({ user }) => {
  const today = new Date();
  const [viewDate, setViewDate] = React.useState(new Date(today.getFullYear(), today.getMonth(), 1));
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [groupBy, setGroupBy] = React.useState('canal'); // 'canal' | 'brand'
  const [brandFilter, setBrandFilter] = React.useState('all');
  const [dragOver, setDragOver] = React.useState(null);

  const monthStart = viewDate;
  const monthEnd = new Date(viewDate.getFullYear(), viewDate.getMonth() + 1, 0);

  const load = React.useCallback(async () => {
    setLoading(true);
    try {
      const params = {
        start: monthStart.toISOString().slice(0, 10),
        end: monthEnd.toISOString().slice(0, 10),
      };
      if (brandFilter !== 'all') params.brand = brandFilter;
      const d = await ActAPI.calendario(params);
      setItems(d?.items || d || []);
    } catch {
      setItems(MOCK_PECAS.map(p => ({
        peca_id: p.id, marca_slug: p.marca_slug, canal_pai: p.canal_pai,
        content_type: p.content_type, scheduled_for: p.scheduled_for,
        thumbnail: p.thumbnail_url, status: p.status, headline: p.headline,
      })));
    } finally {
      setLoading(false);
    }
  }, [viewDate, brandFilter]);

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

  const prevMonth = () => setViewDate(new Date(viewDate.getFullYear(), viewDate.getMonth() - 1, 1));
  const nextMonth = () => setViewDate(new Date(viewDate.getFullYear(), viewDate.getMonth() + 1, 1));

  // Build calendar grid (6 rows × 7 cols)
  const firstDow = monthStart.getDay(); // 0=Sun
  const daysInMonth = monthEnd.getDate();
  const gridCells = Array.from({ length: 42 }, (_, i) => {
    const dayNum = i - firstDow + 1;
    if (dayNum < 1 || dayNum > daysInMonth) return null;
    return dayNum;
  });

  const itemsByDay = React.useMemo(() => {
    const map = {};
    items.forEach(item => {
      if (!item.scheduled_for) return;
      const d = new Date(item.scheduled_for);
      if (d.getMonth() !== viewDate.getMonth() || d.getFullYear() !== viewDate.getFullYear()) return;
      const key = d.getDate();
      if (!map[key]) map[key] = [];
      map[key].push(item);
    });
    return map;
  }, [items, viewDate]);

  const handleDrop = async (dayNum, e) => {
    e.preventDefault();
    const pecaId = e.dataTransfer.getData('peca_id');
    if (!pecaId) return;
    const newDate = new Date(viewDate.getFullYear(), viewDate.getMonth(), dayNum, 9, 0, 0);
    try {
      await ActAPI.reagendar(pecaId, newDate.toISOString(), user.email);
      load();
    } catch (err) { alert(`Erro ao reagendar: ${err.message}`); }
    setDragOver(null);
  };

  const BRAND_OPTS = [
    { value: 'all', label: 'Todas' },
    { value: 'mimaki', label: 'Mimaki' }, { value: 'biond', label: 'BIOND' },
    { value: 'decal', label: 'Decal' }, { value: 'netscreen', label: 'NetScreen' },
  ];

  const DOW = ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'];

  return (
    <div style={{ padding: '24px 32px', display: 'flex', flexDirection: 'column', gap: 16 }}>
      {/* Controls */}
      <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
        <button className="btn btn-xs" onClick={prevMonth} style={{ fontFamily: 'var(--font-body)' }}>Anterior</button>
        <div style={{ fontSize: 15, fontWeight: 700, fontFamily: 'var(--font-display)', color: 'var(--text)', minWidth: 160, textAlign: 'center' }}>
          {viewDate.toLocaleDateString('pt-PT', { month: 'long', year: 'numeric' })}
        </div>
        <button className="btn btn-xs" onClick={nextMonth} style={{ fontFamily: 'var(--font-body)' }}>Seguinte</button>
        <div style={{ marginLeft: 12, display: 'flex', gap: 4 }}>
          {(['canal', 'brand']).map(g => (
            <button key={g} onClick={() => setGroupBy(g)} style={{
              padding: '4px 10px', fontSize: 11, borderRadius: 5, cursor: 'pointer', fontFamily: 'var(--font-body)',
              background: groupBy === g ? 'var(--brand-primary, #3859D0)' : 'var(--bg-elev)',
              color: groupBy === g ? '#fff' : 'var(--text-muted)',
              border: '1px solid var(--border)',
            }}>
              {g === 'canal' ? 'Por canal' : 'Por marca'}
            </button>
          ))}
        </div>
        <ActivacaoDropdown label="Marca" value={brandFilter} options={BRAND_OPTS} onChange={setBrandFilter} />
      </div>

      {loading ? <ActSpinner /> : (
        <div style={{ background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 10, overflow: 'hidden' }}>
          {/* Day-of-week header */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', borderBottom: '1px solid var(--border)' }}>
            {DOW.map(d => (
              <div key={d} style={{ textAlign: 'center', fontSize: 11, fontWeight: 600, color: 'var(--text-muted)', padding: '8px 4px', fontFamily: 'var(--font-mono)', letterSpacing: '0.05em' }}>{d}</div>
            ))}
          </div>
          {/* Grid */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)' }}>
            {gridCells.map((dayNum, i) => {
              const isToday = dayNum && dayNum === today.getDate() && viewDate.getMonth() === today.getMonth() && viewDate.getFullYear() === today.getFullYear();
              const dayItems = dayNum ? (itemsByDay[dayNum] || []) : [];
              const isDragTarget = dragOver === dayNum;
              return (
                <div key={i}
                  onDragOver={e => { if (dayNum) { e.preventDefault(); setDragOver(dayNum); } }}
                  onDragLeave={() => setDragOver(null)}
                  onDrop={e => dayNum && handleDrop(dayNum, e)}
                  style={{
                    minHeight: 90, padding: 6, borderRight: (i + 1) % 7 === 0 ? 'none' : '1px solid var(--border)', borderBottom: '1px solid var(--border)',
                    background: isDragTarget ? 'color-mix(in oklch, var(--brand-primary, #3859D0) 8%, transparent)' : dayNum ? 'transparent' : 'var(--bg-app)',
                    transition: 'background .1s',
                  }}>
                  {dayNum && (
                    <>
                      <div style={{ fontSize: 11.5, fontWeight: isToday ? 700 : 500, color: isToday ? 'var(--brand-primary, #3859D0)' : 'var(--text-muted)', marginBottom: 4 }}>
                        {isToday ? (
                          <span style={{ background: 'var(--brand-primary, #3859D0)', color: '#fff', borderRadius: '50%', width: 20, height: 20, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 11 }}>{dayNum}</span>
                        ) : dayNum}
                      </div>
                      {dayItems.slice(0, 3).map(item => (
                        <div key={item.peca_id}
                          draggable
                          onDragStart={e => e.dataTransfer.setData('peca_id', item.peca_id)}
                          title={item.headline || canalLabel(item.canal_pai)}
                          style={{
                            fontSize: 10, padding: '2px 5px', borderRadius: 4, marginBottom: 2,
                            background: ACT_STATUS[item.status]?.bg || 'rgba(56,89,208,0.1)',
                            color: ACT_STATUS[item.status]?.color || '#3859D0',
                            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                            cursor: 'grab', fontWeight: 500,
                          }}>
                          {canalLabel(item.canal_pai)}
                        </div>
                      ))}
                      {dayItems.length > 3 && (
                        <div style={{ fontSize: 10, color: 'var(--text-dim)', paddingLeft: 2 }}>+{dayItems.length - 3}</div>
                      )}
                    </>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Legend */}
      <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
        {[['approved', 'Aprovada'], ['scheduled', 'Agendada'], ['published', 'Publicada'], ['failed_publish', 'Falhou']].map(([s, l]) => (
          <div key={s} style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
            <div style={{ width: 8, height: 8, borderRadius: '50%', background: ACT_STATUS[s]?.color || '#ccc' }} />
            <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>{l}</span>
          </div>
        ))}
        <div style={{ fontSize: 11, color: 'var(--text-dim)', marginLeft: 8 }}>Arrasta para reagendar</div>
      </div>
    </div>
  );
};

// ═══════════════════════════════════════════════════════════════════════════════
// HISTÓRICO VIEW
// ═══════════════════════════════════════════════════════════════════════════════

const HistoricoView = ({ user }) => {
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [filters, setFilters] = React.useState({ brand: 'all', canal: 'all', periodo: 'last_30d' });

  const load = React.useCallback(async () => {
    setLoading(true);
    const now = new Date();
    let from;
    if (filters.periodo === 'last_7d')   from = new Date(now - 7 * 86400000);
    else if (filters.periodo === 'last_30d') from = new Date(now - 30 * 86400000);
    else if (filters.periodo === 'last_90d') from = new Date(now - 90 * 86400000);
    else from = new Date(now.getFullYear(), now.getMonth(), 1);
    try {
      const params = { from: from.toISOString().slice(0, 10), to: now.toISOString().slice(0, 10) };
      if (filters.brand !== 'all') params.brand = filters.brand;
      if (filters.canal !== 'all') params.canal = filters.canal;
      const d = await ActAPI.historico(params);
      setItems(d?.items || d || []);
    } catch {
      setItems(MOCK_PECAS.filter(p => ['published', 'failed_publish', 'cancelled'].includes(p.status)));
    } finally {
      setLoading(false);
    }
  }, [filters]);

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

  const exportCsv = () => {
    const header = 'Data,Marca,Canal,Headline,URL,Status';
    const rows = items.map(p =>
      [fmtDate(p.scheduled_for || p.created_at), p.marca_slug, p.canal_pai, `"${(p.headline || '').replace(/"/g, '""')}"`, p.published_url || '', p.status].join(',')
    );
    const blob = new Blob([header + '\n' + rows.join('\n')], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a'); a.href = url; a.download = 'activacao_historico.csv'; a.click();
    URL.revokeObjectURL(url);
  };

  const BRAND_OPTS = [
    { value: 'all', label: 'Todas' },
    { value: 'mimaki', label: 'Mimaki' }, { value: 'biond', label: 'BIOND' },
    { value: 'decal', label: 'Decal' }, { value: 'netscreen', label: 'NetScreen' },
  ];
  const CANAL_OPTS = [
    { value: 'all', label: 'Todos' },
    { value: 'instagram', label: 'Instagram' }, { value: 'facebook', label: 'Facebook' },
    { value: 'linkedin', label: 'LinkedIn' }, { value: 'email', label: 'Email' },
    { value: 'meta_ads', label: 'Meta Ads' }, { value: 'muppi_led', label: 'Muppi LED' },
  ];
  const PERIODO_OPTS = [
    { value: 'last_7d', label: 'Últimos 7 dias' },
    { value: 'last_30d', label: 'Últimos 30 dias' },
    { value: 'last_90d', label: 'Últimos 90 dias' },
    { value: 'this_month', label: 'Este mês' },
  ];

  return (
    <div style={{ padding: '24px 32px', display: 'flex', flexDirection: 'column', gap: 16 }}>
      {/* Filters */}
      <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
        <ActivacaoDropdown label="Período" value={filters.periodo} options={PERIODO_OPTS} onChange={v => setFilters(f => ({ ...f, periodo: v }))} />
        <ActivacaoDropdown label="Marca" value={filters.brand} options={BRAND_OPTS} onChange={v => setFilters(f => ({ ...f, brand: v }))} />
        <ActivacaoDropdown label="Canal" value={filters.canal} options={CANAL_OPTS} onChange={v => setFilters(f => ({ ...f, canal: v }))} />
        <div style={{ marginLeft: 'auto' }}>
          <button className="btn btn-xs" onClick={exportCsv} style={{ fontFamily: 'var(--font-body)' }}>Exportar CSV</button>
        </div>
      </div>

      {loading ? <ActSpinner /> : items.length === 0 ? (
        <ActEmptyState icon="history" title="Sem publicações no período" sub="Tenta alargar o período ou mudar os filtros." />
      ) : (
        <div style={{ background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 10, overflow: 'hidden' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ borderBottom: '1px solid var(--border)' }}>
                {['Data', 'Marca', 'Canal', 'Headline', 'URL', 'Estado'].map(h => (
                  <th key={h} style={{ textAlign: 'left', padding: '10px 14px', fontSize: 10.5, fontWeight: 600, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em', whiteSpace: 'nowrap' }}>{h.toUpperCase()}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {items.map((p, i) => (
                <tr key={p.id || i} style={{ borderBottom: '1px solid var(--border)', transition: 'background .1s' }}
                  onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-app)'}
                  onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                  <td style={{ padding: '10px 14px', fontSize: 11.5, color: 'var(--text-muted)', whiteSpace: 'nowrap' }}>{fmtDateShort(p.scheduled_for || p.created_at)}</td>
                  <td style={{ padding: '10px 14px' }}>
                    <span style={{ fontSize: 11.5, fontWeight: 700, color: _actBrandColor(p.marca_slug) }}>{p.marca_slug}</span>
                  </td>
                  <td style={{ padding: '10px 14px', fontSize: 11.5, color: 'var(--text-muted)', whiteSpace: 'nowrap' }}>{canalLabel(p.canal_pai)}</td>
                  <td style={{ padding: '10px 14px', fontSize: 12.5, color: 'var(--text)', maxWidth: 280, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.headline || '—'}</td>
                  <td style={{ padding: '10px 14px' }}>
                    {p.published_url
                      ? <a href={p.published_url} target="_blank" rel="noopener noreferrer" style={{ fontSize: 11.5, color: 'var(--brand-primary)' }}>Ver</a>
                      : <span style={{ fontSize: 11.5, color: 'var(--text-dim)' }}>—</span>
                    }
                  </td>
                  <td style={{ padding: '10px 14px' }}><ActStatusBadge status={p.status} /></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
};

// ═══════════════════════════════════════════════════════════════════════════════
// CONFIG VIEW
// ═══════════════════════════════════════════════════════════════════════════════

const ConfigView = ({ user }) => {
  const scope = getApproverScope(user?.email);
  const isAdmin = scope === 'all';

  const MARCAS = isAdmin
    ? ['mimaki', 'biond', 'decal', 'alldecor', 'sensek', 'netscreen']
    : scope === 'netscreen_only'
    ? ['netscreen']
    : ['mimaki', 'biond', 'decal', 'alldecor', 'sensek'];

  const CANAIS_HEADER = ['Meta FB', 'Meta IG', 'LinkedIn', 'Email / Brevo', 'Muppi LED', 'NovaStar', 'Branddigital'];
  const CANAL_KEYS    = ['meta_fb', 'meta_ig', 'linkedin', 'email', 'muppi_led', 'novastar', 'branddigital'];

  // Map mock contas to matrix
  const getStatus = (marca, canal) => MOCK_CONTAS.find(c => c.marca_slug === marca && c.canal === canal);

  const StatusCell = ({ entry }) => {
    if (!entry) return <td style={{ padding: '10px 14px', textAlign: 'center', color: 'var(--border)', fontSize: 13 }}>—</td>;
    const { status, expira_em, account_name } = entry;
    const color = status === 'ok' ? '#10B981' : status === 'warning' ? '#F59E0B' : '#EF4444';
    return (
      <td style={{ padding: '10px 14px', textAlign: 'center', whiteSpace: 'nowrap' }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3 }}>
          <span style={{ fontSize: 11, fontWeight: 700, color, fontFamily: 'var(--font-mono)' }}>
            {status === 'ok' ? 'OK' : status === 'warning' ? 'AVISO' : 'ERRO'}
          </span>
          {expira_em !== null && expira_em !== undefined && (
            <span style={{ fontSize: 10, color: expira_em < 14 ? '#F59E0B' : 'var(--text-dim)' }}>
              {expira_em}d restantes
            </span>
          )}
          {status === 'warning' && (
            <button className="btn btn-xs" style={{ fontSize: 10, padding: '2px 7px', fontFamily: 'var(--font-body)', color: '#F59E0B', borderColor: '#F59E0B' }}>
              Renovar
            </button>
          )}
          {account_name && <span style={{ fontSize: 9.5, color: 'var(--text-dim)', textAlign: 'center' }}>{account_name}</span>}
        </div>
      </td>
    );
  };

  return (
    <div style={{ padding: '24px 32px', display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div>
        <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text)', fontFamily: 'var(--font-display)', marginBottom: 4 }}>Contas conectadas por marca</div>
        <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>Estado de autenticação das integrações por canal e marca.</div>
      </div>

      {!isAdmin && (
        <div style={{ padding: '10px 16px', background: 'color-mix(in oklch, var(--warning, #F59E0B) 8%, transparent)', border: '1px solid color-mix(in oklch, var(--warning, #F59E0B) 25%, transparent)', borderRadius: 8, fontSize: 12, color: 'var(--text-muted)' }}>
          Estás a ver apenas as contas dentro do teu scope de aprovação.
        </div>
      )}

      <div style={{ background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 10, overflow: 'auto' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 700 }}>
          <thead>
            <tr style={{ borderBottom: '1px solid var(--border)' }}>
              <th style={{ textAlign: 'left', padding: '12px 16px', fontSize: 10.5, fontWeight: 600, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em', width: 100 }}>MARCA</th>
              {CANAIS_HEADER.map(c => (
                <th key={c} style={{ textAlign: 'center', padding: '12px 14px', fontSize: 10.5, fontWeight: 600, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em', whiteSpace: 'nowrap' }}>{c.toUpperCase()}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {MARCAS.map(marca => (
              <tr key={marca} style={{ borderBottom: '1px solid var(--border)' }}>
                <td style={{ padding: '10px 16px' }}>
                  <span style={{ fontSize: 12.5, fontWeight: 700, color: _actBrandColor(marca), textTransform: 'capitalize' }}>{marca}</span>
                </td>
                {CANAL_KEYS.map(canal => (
                  <StatusCell key={canal} entry={getStatus(marca, canal)} />
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Canais legend */}
      <div style={{ padding: '14px 20px', background: 'var(--bg-sunken)', border: '1px solid var(--border)', borderRadius: 8 }}>
        <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-muted)', fontFamily: 'var(--font-mono)', letterSpacing: '0.07em', marginBottom: 8 }}>CANAIS ACTIVOS</div>
        <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
          {[
            { name: 'Meta FB / IG', via: 'Meta Graph API' },
            { name: 'LinkedIn', via: 'LinkedIn API v2' },
            { name: 'Email', via: 'Brevo SMTP/API' },
            { name: 'Muppi LED', via: 'Muppi API' },
            { name: 'NovaStar', via: 'NovaStar CMS (NetScreen)' },
            { name: 'Branddigital', via: 'Branddigital DOOH (NetScreen)' },
          ].map(c => (
            <div key={c.name}>
              <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--text)' }}>{c.name}</div>
              <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>{c.via}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

// ═══════════════════════════════════════════════════════════════════════════════
// ROOT COMPONENT
// ═══════════════════════════════════════════════════════════════════════════════
const MktActivacaoScreen = () => {
  const [view, setView] = React.useState('dashboard');
  const user = React.useMemo(() => getCurrentUser(), []);

  const handleNavigate = (target) => setView(target);

  return (
    <div className="scrollbar" style={{ height: '100%', overflowY: 'auto', display: 'flex', flexDirection: 'column' }}>
      <style>{`
        @keyframes spin   { to { transform: rotate(360deg); } }
        @keyframes pulse  { 0%,100% { opacity: 1; } 50% { opacity: 0.55; } }
      `}</style>
      <ActivacaoHeader user={user} />
      <ActivacaoNav view={view} onChange={setView} />
      <div style={{ flex: 1, minHeight: 0 }}>
        {view === 'dashboard'  && <DashboardView  user={user} onNavigate={handleNavigate} />}
        {view === 'fila'       && <FilaView        user={user} />}
        {view === 'calendario' && <CalendarioView  user={user} />}
        {view === 'historico'  && <HistoricoView   user={user} />}
        {view === 'config'     && <ConfigView      user={user} />}
      </div>
    </div>
  );
};

window.MktActivacaoScreen = MktActivacaoScreen;
