const MktSeoModule = ({ onClose, onOpenChat }) => {
  const brandCtx = window.useMktBrand ? window.useMktBrand() : { brand: 'todas' };
  const [view, setView] = React.useState('resumo');
  const [siteFocus, setSiteFocus] = React.useState(null);
  const [queueCount, setQueueCount] = React.useState(0);
  const [jobs, setJobs] = React.useState([]);

  React.useEffect(() => {
    window.seoFetch('/api/marketing/seo/issues?status=open')
      .then(d => setQueueCount((d.issues || []).filter(i => i.mode !== 'full-auto').length))
      .catch(() => {});
  }, [brandCtx.brand, view]);
  React.useEffect(() => {
    window.seoFetch('/api/marketing/seo/jobs').then(d => setJobs(d.jobs || [])).catch(() => {});
  }, []);

  const goTo = (v, siteId) => {
    setView(v);
    if (siteId) setSiteFocus(siteId);
  };

  const tabs = [
    { id: 'resumo', label: 'Resumo' },
    { id: 'sites', label: 'Sites' },
    { id: 'pesquisas', label: 'Pesquisas' },
    { id: 'ai', label: 'Visibilidade AI' },
    { id: 'conteudos', label: 'Conteúdos' },
    { id: 'queue', label: 'Para aprovar', badge: queueCount },
    { id: 'history', label: 'Histórico' },
    { id: 'config', label: 'Configuração' },
  ];

  const renderView = () => {
    const common = { marca: brandCtx.brand, jobs };
    if (view === 'resumo') return <window.SeoViewResumo onGoTo={goTo} onOpenChat={onOpenChat} {...common} />;
    if (view === 'sites') return <window.SeoViewSites initialSiteId={siteFocus} {...common} />;
    if (view === 'pesquisas') return <window.SeoViewPesquisas {...common} />;
    if (view === 'ai') return <window.SeoViewAi {...common} />;
    if (view === 'conteudos') return <window.SeoViewConteudos {...common} />;
    if (view === 'queue') return <window.SeoViewQueue {...common} />;
    if (view === 'history') return <window.SeoViewHistory {...common} />;
    if (view === 'config') return <window.SeoViewConfig {...common} />;
    return null;
  };

  const st = window.seoSourceStatus(jobs);
  const missing = Object.keys(st.sources).filter(k => !st.sources[k].ok);

  // Cabeçalho e separadores iguais aos de Clipping (Medição): mesmos tamanhos, tokens e classes.
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', minHeight: 0, background: 'var(--bg)' }}>
      <div style={{ background: 'var(--bg-elev)', borderBottom: '1px solid var(--border)', padding: '20px 40px 0', flexShrink: 0 }}>
        <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.07em', color: 'var(--text-muted)', textTransform: 'uppercase', marginBottom: 6, fontFamily: 'var(--font-mono)' }}>
          MARKETING · SEO
        </div>
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16 }}>
          <div>
            <h1 style={{ margin: 0, fontSize: 21, fontWeight: 700, color: 'var(--text)', fontFamily: 'var(--font-display)', letterSpacing: '-0.01em' }}>
              SEO
            </h1>
            <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 4 }}>
              SEO, AEO e GEO nos websites das marcas — o agente mede todas as noites e propõe correcções para aprovar.
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <span role="status" className={'badge ' + (missing.length ? 'badge-warning' : 'badge-success')} title={st.at ? 'Última medição ' + window.seoHora(st.at) : 'Ainda sem medição'}>
              {missing.length ? `${missing.length} de ${Object.keys(st.sources).length} fontes por ligar` : 'Fontes ligadas'}
            </span>
            {onOpenChat ? <button type="button" className="btn" onClick={onOpenChat} style={{ fontSize: 12, height: 32, padding: '0 14px' }}>Falar com a Digi</button> : null}
            <button type="button" className="btn-ai" onClick={() => setView('queue')} style={{ fontSize: 12, height: 32, padding: '0 14px' }}>
              Para aprovar{queueCount ? ` · ${queueCount}` : ''}
            </button>
          </div>
        </div>
        <div style={{ height: 1, background: 'var(--border)', margin: '16px -40px 0' }} />
        <div role="tablist" style={{ display: 'flex', gap: 0, overflowX: 'auto' }}>
          {tabs.map(t => {
            const active = view === t.id;
            return (
              <button key={t.id} type="button" role="tab" aria-selected={active} onClick={() => setView(t.id)} style={{
                background: 'none', border: 'none', outline: 'none', whiteSpace: 'nowrap',
                borderBottom: `2px solid ${active ? 'var(--ai-500)' : 'transparent'}`,
                color: active ? 'var(--text)' : 'var(--text-muted)',
                fontSize: 13, fontWeight: active ? 600 : 500,
                fontFamily: 'var(--font-display)', padding: '10px 18px 12px', cursor: 'pointer',
              }}>
                {t.label}{t.badge > 0 ? <span style={{ marginLeft: 6, fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ai-500)' }}>{t.badge}</span> : null}
              </button>
            );
          })}
        </div>
      </div>
      <div className="scrollbar" style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '24px 40px 40px' }}>
        {renderView()}
      </div>
    </div>
  );
};
window.MktSeoModule = MktSeoModule;
