/* 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) ============
const MktSubAgentes = ({ onOpenChat, onOpenSeo }) => {
  const agents = [
    { id: 'ads',       name: 'ADS',         icon: '📣', color: '#DC2626', status: 'alert',  role: 'Campaign ops cross-marca · Meta + Google + LinkedIn', skills: ['SP_ADS v2', 'FRAME-CAMP'], lastRun: 'Há 12 min', tasks: 11, alert: 'Meta Ads bloqueado · 3 marcas' },
    { 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: 'idle',   role: 'LinkedIn, Instagram, TikTok orgânico', skills: ['SP_SOCIAL v1'], lastRun: 'Há 1d 4h', tasks: 6 },
    { 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' };

  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>
                )}
                <button className="btn btn-xs" onClick={onOpenChat}>
                  <Icon name="sparkle" size={10} />Conversar
                </button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

// ============ Inner: o que vai dentro do MktBrandProvider ============
const MarketingInner = ({ onOpenChat }) => {
  const [sub, setSub] = useSubNav('digi-marketing-sub', 'plano');
  const showPills = sub !== 'agentes';

  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': 'performance', '2': 'plano', '3': 'estrategia', '4': 'agentes' };
      if (e.key === 'Escape' && sub === 'seo-module') { setSub('agentes'); return; }
      if (map[e.key]) setSub(map[e.key]);
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  const Performance = window.MktPerformance;
  const Plano       = window.MktPlanoScreen;
  const Estrategia  = window.MktEstrategia;
  const BrandPills  = window.MktBrandPills;

  const renderSub = () => {
    if (sub === 'performance' && Performance) return <Performance onOpenChat={onOpenChat} />;
    if (sub === 'plano' && Plano)             return <Plano onOpenChat={onOpenChat} />;
    if (sub === 'estrategia' && Estrategia)   return <Estrategia />;
    if (sub === 'agentes')                return <MktSubAgentes onOpenChat={onOpenChat} onOpenSeo={() => setSub('seo-module')} />;
    if (sub === 'seo-module' && window.MktSeoModule) return <window.MktSeoModule onClose={() => setSub('agentes')} onOpenChat={onOpenChat} />;
    return Plano ? <Plano onOpenChat={onOpenChat} /> : null;
  };

  const isSeoModule = sub === 'seo-module';
  const hidePills = !showPills || isSeoModule;

  return (
    <div style={{ background: 'var(--bg)', height: '100%', minHeight: 0, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
      {!hidePills && BrandPills && <BrandPills />}
      <div style={{ flex: 1, minWidth: 0, minHeight: 0, overflow: (sub === 'plano' || isSeoModule) ? 'hidden' : 'auto' }}>
        {renderSub()}
      </div>
    </div>
  );
};

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

window.MarketingScreenWrapper = MarketingScreenWrapper;
