const SeoViewResumo = ({ onGoTo, marca, jobs }) => {
  const { data, err, load } = window.useSeoLoad('/api/marketing/seo/overview', [marca]);
  const [trends, setTrends] = React.useState(null);
  React.useEffect(() => { window.seoFetch('/api/marketing/seo/trends?days=90').then(setTrends).catch(() => setTrends({ scores: [], gsc: [], ranks: [] })); }, [marca]);
  const W = window;
  if (err) return <W.SeoError message={err} onRetry={load} />;
  if (!data) return <W.SeoLoading label="A carregar SEO…" />;
  const sites = data.sites || [];
  if (!sites.length) {
    return <W.SeoCard><W.SeoEmpty title="Ainda não há sites.">Os sites vêm das marcas com website activo (Marcas · websites). Confirma que a marca tem o URL preenchido.</W.SeoEmpty></W.SeoCard>;
  }
  const critical = sites.reduce((n, s) => n + (s.critical || 0), 0);
  const avg = Math.round(sites.reduce((n, s) => n + s.score, 0) / sites.length);
  const cols = 'minmax(180px, 1.6fr) 110px 70px 90px 80px 90px minmax(110px, 1fr)';
  // Média diária do score (snapshots) e totais GSC por dia.
  const byDay = (rows, f) => {
    const m = new Map();
    for (const r of rows || []) { const a = m.get(r.day) || []; a.push(r); m.set(r.day, a); }
    return [...m.keys()].sort().map(d => f(m.get(d)));
  };
  const scoreSeries = byDay(trends?.scores, a => Math.round(a.reduce((n, r) => n + r.score, 0) / a.length));
  const siteSeries = id => (trends?.scores || []).filter(r => r.site_id === id).map(r => r.score);
  const clicks = byDay(trends?.gsc, a => a.reduce((n, r) => n + (r.clicks || 0), 0));
  const impressions = byDay(trends?.gsc, a => a.reduce((n, r) => n + (r.impressions || 0), 0));
  const delta = scoreSeries.length > 1 ? scoreSeries[scoreSeries.length - 1] - scoreSeries[0] : null;
  const recentJobs = (jobs || []).slice(0, 12);
  const jobErrors = (jobs || []).filter(j => j.status === 'error' || j.status === 'partial');
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))', gap: 10 }}>
        <W.SeoStat label="Sites" value={W.seoN(sites.length)} hint="websites das marcas" />
        <W.SeoStat label="Problemas abertos" value={W.seoN(data.open)} hint="em todos os sites" />
        <W.SeoStat label="Críticos" value={W.seoN(critical)} hint="title ou H1 em falta" tone={critical ? W.SEO_C.bad : undefined} />
        <W.SeoStat label="Score médio" value={avg}
          hint={delta == null ? '100 = sem problemas abertos' : `${delta >= 0 ? '+' : ''}${delta} desde ${trends.scores[0].day.slice(5).split('-').reverse().join('/')}`}
          trend={scoreSeries.length > 1 ? <div style={{ marginTop: 6 }}><W.Sparkline values={scoreSeries} width={140} height={24} /></div> : null} />
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1.6fr) minmax(260px, 0.8fr)', gap: 14, alignItems: 'start' }}>
        <W.SeoCard pad={false} style={{ overflowX: 'auto' }}>
          <div style={{ display: 'grid', gridTemplateColumns: cols, gap: 12, padding: '8px 14px', minWidth: 640, borderBottom: '1px solid var(--border)' }}>
            {['Site', 'CMS', 'Score', 'Tendência', 'Críticos', 'Páginas', 'Último crawl'].map(h => <W.SeoTh key={h}>{h}</W.SeoTh>)}
          </div>
          {sites.map(s => (
            <button key={s.id} type="button" onClick={() => onGoTo('sites', s.id)} style={{
              display: 'grid', gridTemplateColumns: cols, gap: 12, alignItems: 'center', width: '100%', minWidth: 640, textAlign: 'left',
              padding: '10px 14px', border: 0, borderBottom: '1px solid var(--border)', background: 'transparent', color: 'var(--text)', font: 'inherit', cursor: 'pointer',
            }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
                <span style={{ width: 8, height: 8, borderRadius: 2, background: s.brand_color || 'var(--text-dim)', flexShrink: 0 }} />
                <span style={{ fontSize: 13, fontWeight: 650, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.domain}</span>
              </span>
              <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>{W.SEO_CMS_LABELS[s.cms] || s.cms}</span>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 13 }}>{s.score}</span>
              <span>{siteSeries(s.id).length > 1 ? <W.Sparkline values={siteSeries(s.id)} width={70} height={18} /> : <span style={{ fontSize: 11, color: 'var(--text-dim)' }}>—</span>}</span>
              <span style={{ fontSize: 13, fontWeight: 650, color: s.critical ? W.SEO_C.bad : 'var(--text-muted)' }}>{s.critical || 0}</span>
              <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>{W.seoN(s.pages)}</span>
              <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>{W.seoHora(s.last_crawl_at)}</span>
            </button>
          ))}
        </W.SeoCard>
        <W.SeoCard>
          <W.SeoEyebrow style={{ marginBottom: 8 }}>Problemas mais comuns</W.SeoEyebrow>
          {(data.top || []).length === 0 && <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>Sem problemas abertos.</div>}
          {(data.top || []).map(t => (
            <div key={t.type + t.severity} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, padding: '7px 0', borderBottom: '1px solid var(--border)', fontSize: 12 }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
                <span style={{ width: 6, height: 6, borderRadius: 99, flexShrink: 0, background: W.seoSeverityColor[t.severity] }} />
                {W.seoTypeLabel(t.type)}
              </span>
              <span style={{ fontFamily: 'var(--font-mono)' }}>{W.seoN(t.count)}<span style={{ color: 'var(--text-dim)' }}> · {t.sites} {t.sites === 1 ? 'site' : 'sites'}</span></span>
            </div>
          ))}
          <div style={{ marginTop: 12 }}><W.SeoButton kind="primary" onClick={() => onGoTo('queue')}>Ver fila para aprovar</W.SeoButton></div>
        </W.SeoCard>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1fr)', gap: 14, alignItems: 'start' }}>
        <div style={{ display: 'grid', gap: 10 }}>
          <W.SeoSection>Search Console · 90 dias</W.SeoSection>
          <W.SeoCard>
            {clicks.length > 1 ? (
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                <div><W.SeoEyebrow>Cliques</W.SeoEyebrow><div className="font-display" style={{ fontSize: 22, fontWeight: 600, margin: '4px 0 6px' }}>{W.seoN(clicks.reduce((a, b) => a + b, 0))}</div><W.Sparkline values={clicks} width={220} height={36} /></div>
                <div><W.SeoEyebrow>Impressões</W.SeoEyebrow><div className="font-display" style={{ fontSize: 22, fontWeight: 600, margin: '4px 0 6px' }}>{W.seoN(impressions.reduce((a, b) => a + b, 0))}</div><W.Sparkline values={impressions} width={220} height={36} color="var(--text-muted)" /></div>
              </div>
            ) : (
              <W.SeoEmpty title="Ainda sem dados do Search Console." action={<W.SeoButton onClick={() => onGoTo('config')}>Ver ligações por site</W.SeoButton>}>
                Os cliques, impressões e posições aparecem depois de a conta de serviço ter acesso às propriedades e da próxima medição nocturna.
              </W.SeoEmpty>
            )}
            {(trends?.ranks || []).length > 0 && (
              <div style={{ marginTop: 12, borderTop: '1px solid var(--border)', paddingTop: 10 }}>
                <W.SeoEyebrow style={{ marginBottom: 6 }}>Melhores posições</W.SeoEyebrow>
                {trends.ranks.slice(0, 6).map(r => (
                  <div key={r.site_id + r.keyword} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, padding: '4px 0' }}>
                    <span>{r.keyword}</span><span style={{ fontFamily: 'var(--font-mono)' }}>{Number(r.position).toFixed(1)}</span>
                  </div>
                ))}
              </div>
            )}
          </W.SeoCard>
        </div>
        <div style={{ display: 'grid', gap: 10 }}>
          <W.SeoSection right={jobErrors.length ? <span className="badge badge-warning">{jobErrors.length} com avisos</span> : null}>Medições recentes</W.SeoSection>
          <W.SeoCard pad={false}>
            {recentJobs.length === 0 ? <W.SeoEmpty title="Ainda não correu nenhuma medição.">O agente corre todas as noites.</W.SeoEmpty> : recentJobs.map(j => (
              <div key={j.id} style={{ padding: '9px 14px', borderBottom: '1px solid var(--border)' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12 }}>
                  <span className={'badge ' + ({ done: 'badge-success', partial: 'badge-warning', error: 'badge-danger', running: 'badge-info' }[j.status] || '')}>{({ done: 'Concluído', partial: 'Parcial', error: 'Erro', running: 'A correr' }[j.status] || j.status)}</span>
                  <span style={{ fontWeight: 600 }}>{j.kind === 'crawl' ? 'Crawl' : j.kind === 'measure' ? 'Medição' : j.kind}</span>
                  <span style={{ color: 'var(--text-muted)' }}>{j.domain || ''}</span>
                  <span style={{ marginLeft: 'auto', color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', fontSize: 11 }}>{W.seoHora(j.finished_at || j.started_at)}</span>
                </div>
                {j.error ? (
                  <div style={{ marginTop: 4, fontSize: 11, color: 'var(--text-muted)', lineHeight: 1.45 }}>
                    {String(j.error).split(' · ').slice(0, 4).map((p, k) => <div key={k}>{p}</div>)}
                  </div>
                ) : null}
              </div>
            ))}
          </W.SeoCard>
        </div>
      </div>
    </div>
  );
};
window.SeoViewResumo = SeoViewResumo;
