/* Marketing · SEO — módulo completo (5 vistas)
   Acessível via: Marketing › Sub-agentes › card "SEO" → onOpen()
   Vistas: Resumo · Sites · Para Aprovar · Histórico · Configuração

   Convenções: dark-first, Inter+Krub+Mono, royal blue para AI,
   linguagem de marketer (sem jargão técnico interno). */

// helpers partilhados vivem em screen_marketing_seo_helpers.jsx (window.SeoBadge, etc.)
const { SeoBadge, SeoTypeBadge, SeoBreadcrumb, Sparkline } = window;

// ──────────────────────────────────────────────────────────────────────────
// VIEW 1 · RESUMO
// ──────────────────────────────────────────────────────────────────────────
const SeoViewResumo = ({ onGoTo, onOpenChat }) => {
  const sites = window.SEO_SITES;
  const totalCritical = sites.reduce((a, s) => a + s.critical, 0);
  const totalMedium   = sites.reduce((a, s) => a + s.medium, 0);
  const totalLow      = sites.reduce((a, s) => a + s.low, 0);
  const totalIssues   = totalCritical + totalMedium + totalLow;
  const avgScore      = Math.round(sites.reduce((a, s) => a + s.score * s.pages, 0) / sites.reduce((a, s) => a + s.pages, 0));
  const trend         = window.SEO_SCORE_TREND;
  const delta         = trend[trend.length - 1] - trend[trend.length - 8];

  const scoreColor = (n) => n >= 80 ? 'var(--success)' : n >= 60 ? 'var(--warning)' : n >= 40 ? '#f97316' : 'var(--danger)';
  const scoreBorder = (n) => n >= 80 ? 'color-mix(in oklch, var(--success) 40%, transparent)'
                          : n >= 60 ? 'color-mix(in oklch, var(--warning) 40%, transparent)'
                          : n >= 40 ? 'color-mix(in oklch, #f97316 40%, transparent)'
                          : 'color-mix(in oklch, var(--danger) 40%, transparent)';

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 20, height: '100%', minHeight: 0 }}>
      {/* coluna principal */}
      <div className="scrollbar" style={{ overflowY: 'auto', padding: '8px 4px 60px' }}>
        {/* HERO · score global */}
        <div className="card" style={{
          padding: 22,
          display: 'grid',
          gridTemplateColumns: '1.1fr 1fr 1fr 1fr',
          gap: 24,
          background: 'linear-gradient(135deg, color-mix(in oklch, var(--ai-500) 6%, transparent), transparent 60%), var(--bg-elev)',
          border: `1px solid ${scoreBorder(avgScore)}`,
        }}>
          <div style={{ borderRight: '1px solid var(--border)', paddingRight: 24 }}>
            <div style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>Score SEO global</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginTop: 6 }}>
              <div className="font-display" style={{ fontSize: 56, fontWeight: 600, lineHeight: 1, letterSpacing: '-0.03em', color: scoreColor(avgScore) }}>{avgScore}</div>
              <div className="font-mono" style={{
                fontSize: 12, color: delta >= 0 ? 'var(--success)' : 'var(--danger)',
                display: 'inline-flex', alignItems: 'center', gap: 3,
              }}>
                <Icon name={delta >= 0 ? 'arrowUp' : 'arrowDown'} size={11} />
                {delta >= 0 ? '+' : ''}{delta} · 7d
              </div>
            </div>
            <div style={{ marginTop: 8 }}>
              <Sparkline values={trend} width={220} height={36} color={scoreColor(avgScore)} />
            </div>
            <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 4 }}>
              5 sites · {sites.reduce((a, s) => a + s.pages, 0)} páginas indexáveis
            </div>
          </div>

          <div>
            <div style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>Issues abertos</div>
            <div className="font-display" style={{ fontSize: 36, fontWeight: 600, marginTop: 6, letterSpacing: '-0.02em' }}>{totalIssues.toLocaleString('pt-PT')}</div>
            <div style={{ display: 'flex', gap: 10, marginTop: 8, fontSize: 11, fontFamily: 'var(--font-mono)' }}>
              <span style={{ color: 'var(--danger)' }}>🔴 {totalCritical}</span>
              <span style={{ color: 'var(--warning)' }}>🟡 {totalMedium.toLocaleString('pt-PT')}</span>
              <span style={{ color: 'var(--success)' }}>🟢 {totalLow}</span>
            </div>
          </div>

          <div>
            <div style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>Aprovações pendentes</div>
            <div className="font-display" style={{ fontSize: 36, fontWeight: 600, marginTop: 6, letterSpacing: '-0.02em' }}>{window.SEO_QUEUE.length}</div>
            <button className="btn btn-xs btn-ai" style={{ marginTop: 8 }} onClick={() => onGoTo('queue')}>
              Abrir queue <Icon name="arrowRight" size={10} />
            </button>
          </div>

          <div>
            <div style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>Aplicados (7d)</div>
            <div className="font-display" style={{ fontSize: 36, fontWeight: 600, marginTop: 6, letterSpacing: '-0.02em', color: 'var(--success)' }}>71</div>
            <button className="btn btn-xs btn-ghost" style={{ marginTop: 8 }} onClick={() => onGoTo('history')}>
              Ver histórico <Icon name="arrowRight" size={10} />
            </button>
          </div>
        </div>

        {/* MAPA DE SITES */}
        <div style={{ marginTop: 22, marginBottom: 10, display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
          <div>
            <div className="font-display" style={{ fontSize: 13, fontWeight: 600, letterSpacing: '0.02em' }}>5 sites</div>
            <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>Última varrida há ~2h · próxima hoje 18:00</div>
          </div>
          <button className="btn btn-sm btn-ai">
            <Icon name="refresh" size={12} /> Lançar audit a todos
          </button>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 12 }}>
          {sites.map(s => (
            <div key={s.id} className="card"
              onClick={() => onGoTo('sites', s.id)}
              style={{
                padding: 14,
                cursor: 'pointer',
                borderLeft: `3px solid ${scoreColor(s.score)}`,
                transition: 'all 0.15s',
              }}
              onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'}
              onMouseLeave={e => e.currentTarget.style.background = 'var(--bg-elev)'}
            >
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
                  <span style={{ width: 8, height: 8, borderRadius: 2, background: s.brandColor, flexShrink: 0 }} />
                  <span className="font-mono" style={{ fontSize: 12, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.domain}</span>
                </div>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 4, flexShrink: 0 }}>
                  <span className="font-display" style={{ fontSize: 18, fontWeight: 600, color: scoreColor(s.score) }}>{s.score}</span>
                  <span className="font-mono" style={{ fontSize: 10, color: s.delta >= 0 ? 'var(--success)' : 'var(--danger)' }}>
                    {s.delta >= 0 ? '↑' : '↓'}{Math.abs(s.delta)}
                  </span>
                </div>
              </div>

              <div style={{ display: 'flex', gap: 8, marginTop: 10, fontSize: 11, fontFamily: 'var(--font-mono)' }}>
                <span style={{ color: s.critical > 0 ? 'var(--danger)' : 'var(--text-dim)' }}>🔴 {s.critical}</span>
                <span style={{ color: 'var(--warning)' }}>🟡 {s.medium}</span>
                <span style={{ color: 'var(--text-muted)' }}>🟢 {s.low}</span>
              </div>

              <div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>
                <span>{s.pages} pgs · {s.langs.join('/')}</span>
                <span>{s.lastCrawl}</span>
              </div>

              <div style={{ marginTop: 8, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span style={{
                  fontSize: 9.5, padding: '1px 6px',
                  background: s.mode === 'Full-auto' ? 'color-mix(in oklch, var(--ai-500) 14%, transparent)'
                    : s.mode === 'Semi-auto' ? 'color-mix(in oklch, var(--info) 14%, transparent)'
                    : 'var(--surface-muted)',
                  color: s.mode === 'Full-auto' ? 'var(--ai-500)' : s.mode === 'Semi-auto' ? 'var(--info)' : 'var(--text-muted)',
                  borderRadius: 3, fontFamily: 'var(--font-mono)',
                  border: '1px solid var(--border)',
                }}>{s.mode}</span>
                <span className="font-mono" style={{ fontSize: 9.5, color: 'var(--text-dim)' }}>abrir →</span>
              </div>
            </div>
          ))}
        </div>

        {/* TOP ISSUES recorrentes */}
        <div style={{ marginTop: 28, marginBottom: 10, display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
          <div className="font-display" style={{ fontSize: 13, fontWeight: 600, letterSpacing: '0.02em' }}>Issues mais frequentes</div>
          <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>agregado dos 5 sites · 27 abr</span>
        </div>

        <div className="card" style={{ overflow: 'hidden' }}>
          {window.SEO_TOP_ISSUES.map((it, i) => {
            const def = window.SEO_ISSUE_TYPES[it.type];
            return (
              <div key={it.type} style={{
                display: 'grid', gridTemplateColumns: '24px 200px 1fr 110px 140px',
                alignItems: 'center', gap: 14,
                padding: '11px 16px',
                borderTop: i === 0 ? 'none' : '1px solid var(--border)',
              }}>
                <SeoBadge severity={it.severity} mini />
                <div>
                  <div className="font-mono" style={{ fontSize: 11.5, fontWeight: 500 }}>{it.type}</div>
                  <div style={{ fontSize: 10.5, color: 'var(--text-muted)', marginTop: 1 }}>{def?.label}</div>
                </div>
                <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>{def?.why}</div>
                <div className="font-mono" style={{ fontSize: 12, textAlign: 'right' }}>
                  <span style={{ fontWeight: 600 }}>{it.count}</span>
                  <span style={{ color: 'var(--text-dim)', marginLeft: 6 }}>· {it.sites} sites</span>
                </div>
                <button className="btn btn-xs btn-ai" style={{ justifySelf: 'end' }}>
                  Corrigir em massa <Icon name="arrowRight" size={10} />
                </button>
              </div>
            );
          })}
        </div>

        {/* Briefing matinal */}
        <div className="ai-surface" style={{ padding: 16, borderRadius: 10, marginTop: 24, display: 'flex', gap: 14 }}>
          <div style={{ width: 32, height: 32, borderRadius: '50%', background: 'color-mix(in oklch, var(--ai-500) 30%, transparent)', display: 'grid', placeItems: 'center', flexShrink: 0, border: '1px solid color-mix(in oklch, var(--ai-500) 50%, transparent)' }}>
            <Icon name="sparkle" size={14} style={{ color: 'var(--ai-500)' }} />
          </div>
          <div style={{ flex: 1 }}>
            <div className="font-display" style={{ fontSize: 12, fontWeight: 600, letterSpacing: '0.02em' }}>Briefing matinal · 08:00</div>
            <div style={{ fontSize: 13, lineHeight: 1.55, color: 'var(--text)', marginTop: 6 }}>
              Bom dia. Hoje no SEO: <strong>8 fixes pendentes</strong> em <span className="font-mono">mimaki.digidelta.pt</span> (1 crítico — title da homepage UCJV330), audit nocturno detectou <strong>+14 broken links</strong> em <span className="font-mono">digidelta.es</span> campanha BIOND. Queres ver o crítico primeiro?
            </div>
            <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
              <button className="btn btn-xs btn-ai" onClick={() => onGoTo('queue')}>Ver crítico</button>
              <button className="btn btn-xs" onClick={() => onGoTo('queue')}>Abrir queue</button>
              <button className="btn btn-xs btn-ghost">Adiar para amanhã</button>
            </div>
          </div>
        </div>
      </div>

      {/* sidebar contextual · "O que a Digi está a fazer agora" */}
      <div className="card" style={{ padding: 14, height: 'fit-content', position: 'sticky', top: 0, alignSelf: 'start' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--ai-halo)', boxShadow: '0 0 8px var(--ai-halo)', animation: 'ai-shimmer 1.6s ease-in-out infinite' }} />
          <div className="font-display" style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>
            O que a Digi está a fazer
          </div>
        </div>
        {window.SEO_JOBS.map(j => {
          const site = window.SEO_SITES.find(s => s.id === j.site);
          const ic = j.kind === 'rewriting' ? '🔄' : j.kind === 'applying' ? '✅' : j.kind === 'awaiting' ? '⏸' : '🔍';
          return (
            <div key={j.id} style={{
              padding: '10px 0', borderTop: '1px solid var(--border)',
              fontSize: 12,
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                <span style={{ fontSize: 12 }}>{ic}</span>
                <span style={{ flex: 1, fontWeight: 500, fontSize: 12 }}>{j.desc}</span>
              </div>
              <div className="font-mono" style={{ fontSize: 10.5, color: 'var(--text-dim)', marginBottom: j.progress != null ? 6 : 0 }}>
                {site?.domain} · {j.eta}
              </div>
              {j.progress != null && (
                <div style={{ height: 3, background: 'var(--surface-muted)', borderRadius: 2, overflow: 'hidden' }}>
                  <div style={{
                    width: `${j.progress}%`, height: '100%',
                    background: j.done ? 'var(--success)' : 'var(--ai-500)',
                    transition: 'width 0.4s ease',
                  }} />
                </div>
              )}
            </div>
          );
        })}

        <div style={{ marginTop: 14, padding: 10, background: 'var(--surface-muted)', borderRadius: 6, fontSize: 11, color: 'var(--text-muted)', lineHeight: 1.5 }}>
          <strong style={{ color: 'var(--text)' }}>Próximo audit</strong><br />
          hoje 18:00 · todos os sites · ~10 min
        </div>

        <button className="btn btn-sm btn-ai" style={{ width: '100%', marginTop: 12, justifyContent: 'center' }} onClick={onOpenChat}>
          <Icon name="sparkle" size={12} /> Falar com a Digi sobre SEO
        </button>
      </div>
    </div>
  );
};

window.SeoViewResumo = SeoViewResumo;
