/* MARKETING wrapper — 4 módulos com brand switcher.
   Performance · Plano · Estratégia · Sub-agentes (transversal, sem switcher).
   Brand state global ao módulo via MktBrandProvider. */

// ============ Sub-agentes (transversal — header esclarece, sem switcher) ============
// Lê o tema actual do portal (localStorage 'digi-theme', padrão 'light')
function getPortalTheme() {
  try { return localStorage.getItem('digi-theme') || 'light'; } catch { return 'light'; }
}

// Constrói URL do agente com o tema actual
function agentUrlWithTheme(baseUrl) {
  return `${baseUrl}?theme=${getPortalTheme()}`;
}



const MktSubAgentes = ({ onOpenChat, onOpenSeo }) => {
  const [openAgent, setOpenAgent] = React.useState(null);
  const iframeRef = React.useRef(null);

  // Observa mudanças de data-theme no <html> e reenvia para o iframe via postMessage
  React.useEffect(() => {
    if (!openAgent) return;
    const obs = new MutationObserver(() => {
      const theme = document.documentElement.dataset.theme || 'light';
      iframeRef.current?.contentWindow?.postMessage({ type: 'digi-theme', theme }, '*');
    });
    obs.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
    return () => obs.disconnect();
  }, [openAgent]);

  const agents = [
    { id: 'ads',       name: 'ADS',         icon: '📣', color: '#DC2626', status: 'active', role: 'Campaign ops cross-marca · Meta + Google + LinkedIn', skills: ['SP_ADS v2', 'FRAME-CAMP'], lastRun: 'Há 12 min', tasks: 11, agentUrl: '/ads-agent/' },
    { id: 'content',   name: 'CONTENT',     icon: '✍', color: '#8B5CF6', status: 'active', role: 'Editorial, copy, briefings ClickUp', skills: ['SP_COLAB_MKT v3', 'FRAME-EDITORIAL'], lastRun: 'Há 4 min', tasks: 42 },
    { id: 'email',     name: 'EMAIL',       icon: '✉', color: '#059669', status: 'active', role: 'Brevo · campanhas + automations transaccionais', skills: ['SP_EMAIL v2', 'FRAME-DRIP'], lastRun: 'Há 1h 8m', tasks: 18 },
    { id: 'seo',       name: 'SEO',         icon: '🔍', color: '#0EA5E9', status: 'active', role: 'Audit técnico + on-page nos 5 sites · propostas accionáveis', skills: ['SP_SEO v1.2', 'FRAME-AUDIT'], lastRun: 'Há 2h', tasks: 47, hasModule: true, openHint: 'Abrir módulo' },
    { id: 'social',    name: 'SOCIAL',      icon: '◉',  color: '#E11D48', status: 'active', role: 'LinkedIn, Instagram, TikTok orgânico', skills: ['SP_SOCIAL v1'], lastRun: 'Há 1d 4h', tasks: 6, agentUrl: 'https://social.digidelta.ai/' },
    { id: 'analytics', name: 'ANALYTICS',   icon: '📊', color: '#3B82F6', status: 'active', role: 'GA4 · Looker · attribution closed-loop', skills: ['SP_ANALYTICS', 'FRAME-KPI'], lastRun: 'Há 22 min', tasks: 14 },
  ];
  const statusColor = { active: 'var(--success)', alert: 'var(--warning)', idle: 'var(--text-dim)' };
  const statusLabel = { active: 'Activo', alert: 'Atenção', idle: 'Inactivo' };

  // Painel iframe para agentes externos
  if (openAgent) {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10,
          padding: '10px 16px', borderBottom: '1px solid var(--border)',
          background: 'var(--bg-elev)', flexShrink: 0,
        }}>
          <button className="btn btn-sm" onClick={() => setOpenAgent(null)} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <Icon name="arrowLeft" size={13} /> Sub-agentes
          </button>
          <span style={{ width: 1, height: 16, background: 'var(--border)' }} />
          <span style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)', letterSpacing: '0.06em' }}>
            AGENTE · {openAgent.name}
          </span>
          <span style={{ flex: 1 }} />
          <a href={agentUrlWithTheme(openAgent.agentUrl)} target="_blank" rel="noopener noreferrer" className="btn btn-sm" style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <Icon name="arrowRight" size={12} /> Abrir em tab
          </a>
        </div>
        <iframe
          ref={iframeRef}
          src={agentUrlWithTheme(openAgent.agentUrl)}
          style={{ flex: 1, border: 'none', width: '100%' }}
          title={`Agente ${openAgent.name}`}
        />
      </div>
    );
  }

  return (
    <div className="scrollbar" style={{ padding: '20px 24px 80px', height: '100%', overflowY: 'auto' }}>
      <div style={{ fontSize: 11, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em' }}>MARKETING · SUB-AGENTES</div>
      <h2 className="font-display" style={{ margin: '6px 0 4px', fontSize: 28, fontWeight: 500, letterSpacing: '-0.01em' }}>
        Agentes transversais
      </h2>
      <div style={{ fontSize: 12, color: 'var(--text-muted)', marginBottom: 6, maxWidth: 720 }}>
        Operam em todas as marcas. Cada sub-agente Digi é treinado num playbook (ADS, EMAIL, SEO, SOCIAL, CONTENT, ANALYTICS) e invocável por Digi Marketing ou directamente em chat.
      </div>
      <div style={{
        padding: '8px 12px', borderRadius: 6, marginBottom: 18,
        background: 'color-mix(in oklch, var(--ai-500) 8%, transparent)',
        border: '1px solid color-mix(in oklch, var(--ai-500) 24%, transparent)',
        fontSize: 11.5, color: 'var(--text-muted)',
        display: 'inline-flex', alignItems: 'center', gap: 8,
      }}>
        <Icon name="info" size={13} style={{ color: 'var(--ai-500)' }} />
        Os sub-agentes não filtram por marca — actuam transversalmente. Para análise específica de uma marca, abra Performance / Plano / Estratégia e seleccione a marca em cima.
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))', gap: 14 }}>
        {agents.map(a => (
          <div key={a.id} className="card" style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 10 }}>
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
              <div style={{
                width: 48, height: 48, borderRadius: 10,
                background: `${a.color}18`, color: a.color,
                display: 'grid', placeItems: 'center', fontSize: 22,
                flexShrink: 0, border: `1px solid ${a.color}30`,
              }}>{a.icon}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="font-display" style={{ fontSize: 15, fontWeight: 600, letterSpacing: '0.01em' }}>{a.name}</div>
                <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2, lineHeight: 1.4 }}>{a.role}</div>
              </div>
              <div style={{
                display: 'inline-flex', alignItems: 'center', gap: 5,
                padding: '2px 8px', borderRadius: 999, fontSize: 10,
                background: `color-mix(in oklch, ${statusColor[a.status]} 14%, transparent)`,
                color: statusColor[a.status], fontFamily: 'var(--font-mono)', flexShrink: 0,
              }}>
                <span style={{ width: 5, height: 5, borderRadius: '50%', background: statusColor[a.status] }} />
                {statusLabel[a.status]}
              </div>
            </div>

            {a.alert && (
              <div style={{ padding: '6px 8px', background: 'color-mix(in oklch, var(--warning) 12%, transparent)', borderRadius: 5, fontSize: 11, color: 'var(--warning)' }}>
                ⚠ {a.alert}
              </div>
            )}

            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
              {a.skills.map((s, i) => (
                <span key={i} className="font-mono" style={{
                  padding: '2px 6px', fontSize: 9.5,
                  background: 'var(--bg-sunken)', color: 'var(--text-muted)',
                  borderRadius: 3, border: '1px solid var(--border)',
                }}>{s}</span>
              ))}
            </div>

            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: 8, borderTop: '1px solid var(--border)' }}>
              <span className="font-mono" style={{ fontSize: 10.5, color: 'var(--text-dim)' }}>
                {a.tasks} tarefas · último run {a.lastRun}
              </span>
              <div style={{ display: 'flex', gap: 6 }}>
                {a.hasModule && (
                  <button className="btn btn-xs btn-ai" onClick={() => a.id === 'seo' && onOpenSeo && onOpenSeo()}>
                    <Icon name="arrowRight" size={10} />{a.openHint}
                  </button>
                )}
                {a.agentUrl ? (
                  <button className="btn btn-xs btn-primary" onClick={() => setOpenAgent(a)}>
                    <Icon name="sparkle" size={10} />Conversar
                  </button>
                ) : (
                  <button className="btn btn-xs" onClick={onOpenChat}>
                    <Icon name="sparkle" size={10} />Conversar
                  </button>
                )}
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

function useMktZoneLoading(active) {
  const id = React.useId();
  React.useLayoutEffect(() => {
    const report = window.__mktGateReport;
    if (typeof report !== 'function') return undefined;
    report(id, !!active);
    return () => report(id, false);
  }, [id, active]);
}
window.useMktZoneLoading = useMktZoneLoading;

function MktModuleZone({ children }) {
  return children;
}

// ============ Placeholder para ecrãs ainda não construídos ============
const MktComingSoon = ({ label }) => (
  <div style={{ padding: 48, textAlign: 'center', color: 'var(--text-muted)' }}>
    <div className="font-display" style={{ fontSize: 18, color: 'var(--text)', marginBottom: 8 }}>{label}</div>
    <div style={{ fontSize: 13 }}>Em construção.</div>
  </div>
);

// ============ Overview — ecrã inicial do módulo ============
const MktOverview = ({ setSub }) => (
  <div style={{ padding: 32, display: 'flex', flexDirection: 'column', gap: 24 }}>
    <div>
      <div className="font-display" style={{ fontSize: 22, color: 'var(--text)', marginBottom: 4 }}>Marketing</div>
      <div style={{ color: 'var(--text-muted)', fontSize: 14 }}>Selecciona um módulo para começar.</div>
    </div>
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 12 }}>
      {[
        { id: 'marcas',          label: 'Marcas',         desc: '5 PMs · dashboard por marca' },
        { id: 'objectivos',      label: 'Objectivos',     desc: 'Business Plan vs real' },
        { id: 'briefings',       label: 'Briefings',      desc: 'Knowledge base por marca' },
        { id: 'conteudos',       label: 'Conteúdos',      desc: 'AI Strategist · gate RL' },
        { id: 'producao',        label: 'Produção',        desc: 'FLUX · Puppeteer · R2' },
        { id: 'publicacao',      label: 'Publicação',     desc: 'Execução multi-canal' },
        { id: 'ligacoes',        label: 'Ligações',       desc: 'Apps, APIs e contas' },
        { id: 'sdr',             label: 'SDR AI',         desc: 'Supervisão da Digi' },
        { id: 'sdr-humano',      label: 'SDR Suporte',    desc: 'Campanhas no ar e formação' },
        { id: 'resultados',      label: 'Resultados',     desc: 'Campanhas no ar vs objectivos' },
      ].map(item => (
        <div key={item.id} className="card" onClick={() => setSub(item.id)}
          style={{ padding: 16, cursor: 'pointer' }}
          onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'}
          onMouseLeave={e => e.currentTarget.style.background = ''}>
          <div style={{ fontWeight: 600, color: 'var(--text)', marginBottom: 4 }}>{item.label}</div>
          <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{item.desc}</div>
        </div>
      ))}
    </div>
  </div>
);

// ============ Error boundary — isola crashes de sub-screens ============
class MktErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }
  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }
  componentDidCatch(error, info) {
    console.error('[MktErrorBoundary]', this.props.label || 'sub-screen', error, info);
  }
  render() {
    if (this.state.hasError) {
      return (
        <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-muted)' }}>
          <div style={{ fontSize: 36, opacity: 0.3, marginBottom: 16 }}>⚠</div>
          <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 8, color: 'var(--text)' }}>
            {this.props.label || 'Este módulo'} teve um erro
          </div>
          <div style={{ fontSize: 12, marginBottom: 16 }}>
            {this.state.error?.message || 'Erro desconhecido'}
          </div>
          <button
            className="btn btn-sm"
            onClick={() => this.setState({ hasError: false, error: null })}
          >Tentar de novo</button>
        </div>
      );
    }
    return this.props.children;
  }
}

// ============ Inner: o que vai dentro do MktBrandProvider ============
function mktPodeVerActividade(user, userTipo) {
  const tipo = userTipo || user?.tipo || user?.tipo_utilizador || '';
  const modos = user?.modos || user?.modos_acesso || [];
  const elevados = ['admin', 'chairman', 'c_suite', 'director', 'manager'];
  return elevados.includes(tipo) || modos.includes('dev') || modos.includes('admin');
}

const MarketingInner = ({ onOpenChat, userName, userTipo, user }) => {
  const [sub, setSubRaw] = useSubNav('digi-marketing-sub', 'inicio');
  const subRef = React.useRef(sub);
  subRef.current = sub;
  const hashAntes = React.useRef(window.location.hash);
  React.useEffect(() => { hashAntes.current = window.location.hash; }, [sub]);
  const irSub = (next) => {
    const value = typeof next === 'function' ? next(subRef.current) : next;
    if (!value || value === subRef.current) return true;
    const go = () => setSubRaw(value);
    if (subRef.current === 'briefings' && value !== 'briefings' && typeof window.mktPedirSaidaBriefing === 'function' && window.mktPedirSaidaBriefing(go) === false) return false;
    go();
    return true;
  };
  const irSubRef = React.useRef(irSub);
  irSubRef.current = irSub;
  const setSub = irSub;
  const [mktUserEmail, setMktUserEmail] = React.useState(user?.email || null);
  const BrandPills = window.MktBrandPills;

  React.useEffect(() => {
    const q = new URLSearchParams(window.location.search || '');
    if (!q.get('dev') && !q.get('mkt_role')) {
      if (user?.email) setMktUserEmail(user.email);
      return;
    }
    fetch('/api/marketing/me' + (window.location.search || ''))
      .then(r => r.ok ? r.json() : null)
      .then(u => { if (u?.email) setMktUserEmail(u.email); })
      .catch(() => {});
  }, [user]);

  React.useEffect(() => {
    if (user && typeof user === 'object') window.currentUser = user;
  }, [user]);

  React.useEffect(() => {
    window.mktNavToSub = (next) => irSubRef.current(next);
    return () => { delete window.mktNavToSub; };
  }, []);

  React.useEffect(() => {
    const nav = window.NAV_MAP && window.NAV_MAP.marketing;
    if (nav && Array.isArray(nav.sub) && !nav.sub.some(s => s.id === 'ligacoes')) {
      nav.sub.push({ section: 'SETUP' });
      nav.sub.push({ id: 'ligacoes', label: 'Ligações', kbd: 'L' });
    }
    let stop = false;
    const refreshBadge = () => {
      const p = new URLSearchParams(window.location.search || '');
      const email = window.currentUser?.email || '';
      if (email && !p.get('email')) p.set('email', email);
      fetch('/api/marketing/ligacoes/summary?' + p.toString(), { credentials: 'same-origin' })
        .then(r => r.ok ? r.json() : null)
        .then(d => {
          if (stop || !d) return;
          const item = nav?.sub?.find(s => s.id === 'ligacoes');
          if (!item) return;
          const n = Number(d.atencao || 0);
          item.badge = n > 0 ? String(n) : undefined;
          window.dispatchEvent(new Event('portal-nav-refresh'));
        })
        .catch(() => {});
    };
    refreshBadge();
    const timer = setInterval(refreshBadge, 5 * 60 * 1000);
    return () => { stop = true; clearInterval(timer); };
  }, []);

  React.useEffect(() => {
    const nav = window.NAV_MAP && window.NAV_MAP.marketing;
    if (!nav || !Array.isArray(nav.sub)) return;
    const pode = mktPodeVerActividade(user, userTipo);
    const idx = nav.sub.findIndex(s => s.id === 'actividade');
    if (pode && idx < 0) {
      const item = { id: 'actividade', label: 'Actividade' };
      const lig = nav.sub.findIndex(s => s.id === 'ligacoes');
      if (lig >= 0) nav.sub.splice(lig + 1, 0, item);
      else {
        if (!nav.sub.some(s => s.section === 'SETUP')) nav.sub.push({ section: 'SETUP' });
        nav.sub.push(item);
      }
      window.dispatchEvent(new Event('portal-nav-refresh'));
    } else if (!pode && idx >= 0) {
      nav.sub.splice(idx, 1);
      window.dispatchEvent(new Event('portal-nav-refresh'));
    }
  }, [user, userTipo]);

  React.useEffect(() => {
    let stop = false;
    const send = (abriu) => {
      fetch('/api/marketing/actividade/presenca', {
        method: 'POST',
        credentials: 'same-origin',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ modulo: sub, abriu: !!abriu }),
      }).catch(() => {});
    };
    send(true);
    const timer = setInterval(() => { if (!stop) send(false); }, 45000);
    return () => { stop = true; clearInterval(timer); };
  }, [sub]);

  React.useEffect(() => {
    const applyHash = () => {
      try {
        const q = new URLSearchParams(window.location.hash.replace(/^#/, ''));
        if (q.get('screen') && q.get('screen') !== 'marketing') return;
        const hashSub = q.get('sub');
        if (!hashSub) return;
        if (irSubRef.current(hashSub) === false) {
          const back = hashAntes.current || '#screen=marketing&sub=briefings';
          const href = String(back).startsWith('#') ? back : '#' + back;
          if (window.location.hash !== href) history.replaceState(null, '', href);
        }
      } catch {}
    };
    applyHash();
    window.addEventListener('hashchange', applyHash);
    return () => window.removeEventListener('hashchange', applyHash);
  }, []);

  React.useEffect(() => {
    const onKey = (e) => {
      if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
      if (e.metaKey || e.ctrlKey || e.altKey) return;
      const map = { '1': 'inicio', '2': 'objectivos', '3': 'resultados', '4': 'marcas', '5': 'plano-comunicacao', '6': 'briefings', '7': 'campanhas', '8': 'conteudos', '9': 'publicacao', l: 'ligacoes', L: 'ligacoes', a: 'audiencias', A: 'audiencias', c: 'leads-outbound', C: 'leads-outbound', i: 'leads-inbound', I: 'leads-inbound', b: 'sdr', B: 'sdr', s: 'sdr-humano', S: 'sdr-humano', p: 'prospeccao', P: 'prospeccao', t: 'chamada-teste', T: 'chamada-teste' };
      const dest = map[e.key];
      if (!dest) return;
      try {
        const prev = new URLSearchParams(String(window.location.hash || '').replace(/^#/, ''));
        const next = new URLSearchParams();
        next.set('screen', 'marketing');
        next.set('sub', dest);
        const marca = prev.get('marca');
        if (marca) next.set('marca', marca);
        const href = next.toString();
        if (String(window.location.hash || '').replace(/^#/, '') !== href) window.location.hash = href;
        else irSubRef.current(dest);
      } catch {}
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  const renderSub = () => {
    if (sub === 'inicio')          return window.MktInicioScreen       ? <window.MktInicioScreen setSub={setSub} userName={userName} userEmail={mktUserEmail} /> : <MktOverview setSub={setSub} />;
    if (sub === 'marcas')          return window.MktMarcasScreen       ? <window.MktMarcasScreen />                                          : <MktComingSoon label="Marcas" />;
    if (sub === 'objectivos')      return window.MktObjectivosScreen   ? <window.MktObjectivosScreen userName={userName} />                   : <MktComingSoon label="Objectivos" />;
    if (sub === 'briefings')       return window.MktBriefingsScreen    ? <window.MktBriefingsScreen userName={userName} userTipo={userTipo} userEmail={mktUserEmail} onNavToSub={setSub} /> : <MktComingSoon label="Briefings" />;
    if (sub === 'campanhas')       return window.MktCampanhasScreen    ? <window.MktCampanhasScreen onOpenChat={onOpenChat} userEmail={mktUserEmail} user={user} userTipo={userTipo} /> : <MktComingSoon label="Campanhas" />;
    if (sub === 'conteudos')       return window.MktConteudosScreen    ? <window.MktConteudosScreen userEmail={mktUserEmail} />              : <MktComingSoon label="Produção de Conteúdos" />;
    if (sub === 'estrategia')      return (
      <div style={{ padding: 48, textAlign: 'center', color: 'var(--text)' }}>
        <div style={{ fontSize: 16, fontWeight: 700, marginBottom: 8 }}>A estratégia de campanha faz-se em Campanhas.</div>
        <button className="btn btn-ai" onClick={() => setSub('campanhas')}>Abrir Campanhas</button>
      </div>
    );
    if (sub === 'plano-comunicacao') return window.MktPlanoComunicacaoScreen ? <window.MktPlanoComunicacaoScreen userEmail={mktUserEmail} /> : <MktComingSoon label="Plano de Comunicação" />;
    if (sub === 'publicacao')      return window.MktActivacaoScreen    ? <window.MktActivacaoScreen />                                       : <MktComingSoon label="Publicação" />;
    if (sub === 'analise-campanhas') return window.MktAnaliseCampanhasScreen ? <window.MktAnaliseCampanhasScreen /> : <MktComingSoon label="Análise de campanhas" />;
    if (sub === 'ligacoes')        return window.MktLigacoesScreen     ? <window.MktLigacoesScreen />                                        : <MktComingSoon label="Ligações" />;
    if (sub === 'actividade')      return window.MktActividadeScreen   ? <window.MktActividadeScreen />                                      : <MktComingSoon label="Actividade" />;
    if (sub === 'open-houses')     return window.MktOpenHousesScreen   ? <window.MktOpenHousesScreen userName={userName} userEmail={mktUserEmail} />                : <MktComingSoon label="Open Houses" />;
    if (sub === 'sdr') {
      const SdrScreen = window.MktSdrScreen || window.MktLeadsScreen;
      return SdrScreen ? <SdrScreen /> : <MktComingSoon label="SDR AI" />;
    }
    if (sub === 'sdr-humano')  return window.MktSdrHumanoScreen ? <window.MktSdrHumanoScreen userEmail={mktUserEmail} /> : <MktComingSoon label="SDR Suporte" />;
    if (sub === 'prospeccao')      return window.MktProspeccaoScreen   ? <window.MktProspeccaoScreen />                                      : <MktComingSoon label="Prospeção" />;
    if (sub === 'resultados' || sub === 'performance-ads') return window.MktPerformance360Screen ? <window.MktPerformance360Screen setSub={setSub} onOpenChat={onOpenChat} userName={userName} /> : <MktComingSoon label="Resultados" />;
    if (sub === 'resultados-analise') return window.MktResultadosAnaliseScreen ? <window.MktResultadosAnaliseScreen setSub={setSub} /> : <MktComingSoon label="Análise de Resultados" />;
    if (sub === 'resultados-mimaki') return window.MktResultadosMimakiScreen ? <window.MktResultadosMimakiScreen setSub={setSub} userEmail={mktUserEmail} /> : <MktComingSoon label="Report Mimaki" />;
    if (sub === 'resultados-faturado') return window.MktResultadosFaturadoScreen ? <window.MktResultadosFaturadoScreen setSub={setSub} /> : <MktComingSoon label="Faturado e investimento" />;
    if (sub === 'budget')          return window.MktBudgetScreen       ? <window.MktBudgetScreen />              : <MktComingSoon label="Budget" />;
    if (sub === 'crm' || sub === 'audiencias') return window.MktCRMScreen ? <window.MktCRMScreen userName={userName} surface="audiencias" /> : <MktComingSoon label="Audiências" />;
    if (sub === 'leads-outbound' || sub === 'leads-campanhas') return window.MktLeadsControlScreen ? <window.MktLeadsControlScreen userName={userName} userEmail={mktUserEmail} modulo="outbound" /> : <MktComingSoon label="Outbound" />;
    if (sub === 'leads-inbound') return window.MktLeadsControlScreen ? <window.MktLeadsControlScreen userName={userName} userEmail={mktUserEmail} modulo="inbound" /> : <MktComingSoon label="Inbound" />;
    if (sub === 'clipping')        return window.MktClippingScreen     ? <window.MktClippingScreen userName={userName} />                                     : <MktComingSoon label="Clipping" />;
    if (sub === 'seo')             return window.MktSeoModule          ? <window.MktSeoModule onClose={() => setSub('inicio')} onOpenChat={onOpenChat} />     : <MktComingSoon label="SEO" />;
    if (sub === 'chamada-teste')   return window.MktChamadaTesteScreen ? <window.MktChamadaTesteScreen userEmail={user?.email || mktUserEmail || ''} /> : <MktComingSoon label="Chamada teste" />;
    return <MktOverview setSub={setSub} />;
  };

  return (
    <div style={{ background: 'var(--bg)', height: '100%', minHeight: 0, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
      {BrandPills && sub !== 'inicio' && sub !== 'briefings' && sub !== 'resultados' && sub !== 'resultados-analise' && sub !== 'resultados-mimaki' && sub !== 'resultados-faturado' && sub !== 'performance-ads' && sub !== 'conteudos' && sub !== 'campanhas' && sub !== 'publicacao' && sub !== 'analise-campanhas' && sub !== 'ligacoes' && sub !== 'actividade' && sub !== 'plano-comunicacao' && sub !== 'open-houses' && sub !== 'sdr' && sub !== 'sdr-humano' && sub !== 'prospeccao' && sub !== 'audiencias' && sub !== 'leads-campanhas' && sub !== 'leads-outbound' && sub !== 'leads-inbound' && sub !== 'crm' && sub !== 'budget' && sub !== 'chamada-teste' && <BrandPills />}
      <div style={{ flex: 1, minWidth: 0, minHeight: 0, overflow: 'hidden' }}>
        <MktModuleZone sub={sub}>
          <MktErrorBoundary label={sub} key={sub}>
            {renderSub()}
          </MktErrorBoundary>
        </MktModuleZone>
      </div>
      {window.MktDigiDock && <window.MktDigiDock sub={sub} userName={userName} userEmail={mktUserEmail} />}
    </div>
  );
};

// ============ Outer wrapper ============
const MarketingScreenWrapper = ({ variation, onOpenChat, userName, userTipo, user }) => {
  const Provider = window.MktBrandProvider;
  if (!Provider) return <MarketingInner onOpenChat={onOpenChat} userName={userName} userTipo={userTipo} user={user} />;
  return (
    <Provider>
      <MarketingInner onOpenChat={onOpenChat} userName={userName} userTipo={userTipo} user={user} />
    </Provider>
  );
};

window.MarketingScreenWrapper = MarketingScreenWrapper;

(function mktEnsureLigacoesNav() {
  const nav = window.NAV_MAP && window.NAV_MAP.marketing;
  if (!nav || !Array.isArray(nav.sub)) return;
  if (nav.sub.some(s => s.id === 'ligacoes')) return;
  nav.sub.push({ section: 'SETUP' });
  nav.sub.push({ id: 'ligacoes', label: 'Ligações', kbd: 'L' });
  const cat = Array.isArray(window.PORTAL_NAV_CATALOG)
    ? window.PORTAL_NAV_CATALOG.find(x => x.id === 'marketing')
    : null;
  if (cat && Array.isArray(cat.sub) && !cat.sub.some(s => s.id === 'ligacoes')) {
    cat.sub.push({ id: 'ligacoes', label: 'Ligações' });
  }
})();
