/* SEO · vistas Sites + Queue + History + Config + Drawer */

// helpers partilhados (em screen_marketing_seo_helpers.jsx)
const { SeoBadge, SeoTypeBadge, seoSeverityLabel, seoSeverityColor } = window;

// ──────────────────────────────────────────────────────────────────────────
// Drawer · detalhe de issue (partilhado entre Sites e Queue)
// ──────────────────────────────────────────────────────────────────────────
const SeoIssueDrawer = ({ item, onClose, onApprove, onReject }) => {
  if (!item) return null;
  const site = window.SEO_SITES.find(s => s.id === item.site);
  const def = window.SEO_ISSUE_TYPES[item.type] || {};

  return (
    <>
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)',
        zIndex: 200, animation: 'fadeIn 0.18s ease',
      }} />
      <div className="scrollbar" style={{
        position: 'fixed', top: 0, right: 0, bottom: 0,
        width: 560, maxWidth: '95vw',
        background: 'var(--bg-elev)',
        borderLeft: '1px solid var(--border)',
        zIndex: 201,
        display: 'flex', flexDirection: 'column',
        animation: 'slideInRight 0.22s cubic-bezier(0.2, 0.8, 0.2, 1)',
        overflow: 'hidden',
      }}>
        {/* header */}
        <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0 }}>
          <SeoBadge severity={item.severity} />
          <SeoTypeBadge type={item.type} />
          <span style={{ flex: 1 }} />
          <span style={{ fontSize: 11, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>{item.age}</span>
          <button onClick={onClose} className="btn btn-xs btn-ghost"><Icon name="close" size={12} /></button>
        </div>

        <div className="scrollbar" style={{ flex: 1, overflowY: 'auto', padding: '18px 22px 32px' }}>
          {/* SECÇÃO 1 · A página */}
          <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 10 }}>
            A página
          </div>
          <div style={{ display: 'flex', gap: 14, marginBottom: 18 }}>
            {/* placeholder thumbnail */}
            <div style={{
              width: 120, height: 90, borderRadius: 6, flexShrink: 0,
              background: 'var(--surface-muted)',
              border: '1px solid var(--border)',
              display: 'grid', placeItems: 'center',
              color: 'var(--text-dim)', fontSize: 9, fontFamily: 'var(--font-mono)',
              backgroundImage: 'repeating-linear-gradient(45deg, color-mix(in oklch, var(--border) 50%, transparent) 0 1px, transparent 1px 8px)',
            }}>preview</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="font-mono" style={{ fontSize: 12, color: 'var(--ai-400)', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                https://{site?.domain}{item.url}
              </div>
              <div style={{ display: 'flex', gap: 8, marginTop: 8, flexWrap: 'wrap' }}>
                <span className="badge">{item.lang}</span>
                <span className="badge">{item.section}</span>
                <span className="badge" style={{ background: `${site?.brandColor}22`, color: site?.brandColor, border: `1px solid ${site?.brandColor}40` }}>{site?.brand}</span>
              </div>
              <div style={{ marginTop: 8, display: 'flex', gap: 6 }}>
                <button className="btn btn-xs"><Icon name="copy" size={10} /> copiar URL</button>
                <button className="btn btn-xs"><Icon name="globe" size={10} /> abrir</button>
              </div>
            </div>
          </div>

          {/* SECÇÃO 2 · O issue */}
          <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 10 }}>
            O que está mal
          </div>
          <div className="card" style={{ padding: 14, marginBottom: 18 }}>
            <div className="font-display" style={{ fontSize: 14, fontWeight: 600 }}>{def.label}</div>
            <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 6, lineHeight: 1.55 }}>
              {def.why}
            </div>
            {item.context && (
              <div style={{ marginTop: 10, padding: '8px 10px', background: 'var(--surface-muted)', borderRadius: 6, fontSize: 11.5, fontStyle: 'italic', color: 'var(--text-muted)', borderLeft: '2px solid var(--border-strong)' }}>
                {item.context}
              </div>
            )}
          </div>

          {/* SECÇÃO 3 · Proposta da Digi */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 10 }}>
            <Icon name="sparkle" size={11} style={{ color: 'var(--ai-500)' }} />
            <div style={{ fontSize: 10, color: 'var(--ai-400)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>
              Proposta da Digi
            </div>
          </div>

          {/* before / after */}
          <div style={{ marginBottom: 10 }}>
            <div style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', marginBottom: 4 }}>ANTES</div>
            <div style={{
              padding: '10px 12px',
              background: 'color-mix(in oklch, var(--danger) 6%, var(--surface-muted))',
              border: '1px solid color-mix(in oklch, var(--danger) 24%, var(--border))',
              borderRadius: 6,
              fontSize: 12.5, color: 'var(--text)', lineHeight: 1.5,
              fontFamily: 'var(--font-mono)',
            }}>{item.before}</div>
          </div>
          <div style={{ marginBottom: 12 }}>
            <div style={{ fontSize: 10.5, color: 'var(--ai-400)', fontFamily: 'var(--font-mono)', marginBottom: 4 }}>DEPOIS · proposta</div>
            <div style={{
              padding: '10px 12px',
              background: 'color-mix(in oklch, var(--ai-500) 8%, transparent)',
              border: '1px solid color-mix(in oklch, var(--ai-500) 30%, transparent)',
              borderRadius: 6,
              fontSize: 12.5, color: 'var(--text)', lineHeight: 1.5,
              fontFamily: 'var(--font-mono)',
            }}>{item.after}</div>
          </div>

          <div style={{ padding: '10px 12px', background: 'var(--surface-muted)', borderRadius: 6, fontSize: 11.5, color: 'var(--text-muted)', marginBottom: 16, lineHeight: 1.5 }}>
            <strong style={{ color: 'var(--text)' }}>Porque esta proposta:</strong> {item.why}
          </div>

          {item.related > 0 && (
            <div style={{
              padding: '10px 12px',
              background: 'color-mix(in oklch, var(--info) 8%, transparent)',
              border: '1px solid color-mix(in oklch, var(--info) 24%, transparent)',
              borderRadius: 6, fontSize: 11.5, marginBottom: 16,
              display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10,
            }}>
              <span style={{ color: 'var(--text)' }}>
                <Icon name="layers" size={11} style={{ color: 'var(--info)', verticalAlign: '-2px', marginRight: 5 }} />
                Existem <strong>{item.related} outras propostas</strong> do mesmo padrão na queue.
              </span>
              <button className="btn btn-xs btn-ai">Aprovar todas</button>
            </div>
          )}

          {item.blocks && item.blocks.length > 0 && (
            <div style={{
              padding: '10px 12px',
              background: 'color-mix(in oklch, var(--warning) 10%, transparent)',
              border: '1px solid color-mix(in oklch, var(--warning) 28%, transparent)',
              borderRadius: 6, fontSize: 11.5, color: 'var(--warning)',
            }}>
              <Icon name="warning" size={11} style={{ verticalAlign: '-2px', marginRight: 5 }} />
              {item.blocks.join(' · ')}
            </div>
          )}
        </div>

        {/* footer · acções */}
        <div style={{ padding: '12px 18px', borderTop: '1px solid var(--border)', display: 'flex', gap: 8, flexShrink: 0, background: 'var(--bg-sunken)' }}>
          <button className="btn btn-sm btn-ai" style={{ flex: 1, justifyContent: 'center' }} onClick={() => onApprove(item)}>
            <Icon name="check" size={12} /> Aprovar e aplicar
          </button>
          <button className="btn btn-sm" title="Editar antes de aplicar"><Icon name="wrench" size={12} /></button>
          <button className="btn btn-sm" title="Pedir alternativa"><Icon name="refresh" size={12} /></button>
          <button className="btn btn-sm btn-ghost" onClick={() => onReject(item)} title="Ignorar"><Icon name="close" size={12} /></button>
        </div>
      </div>
    </>
  );
};

// ──────────────────────────────────────────────────────────────────────────
// VIEW 2 · SITES (drill-down)
// ──────────────────────────────────────────────────────────────────────────
const SeoViewSites = ({ initialSiteId }) => {
  const [siteId, setSiteId] = React.useState(initialSiteId || window.SEO_SITES[0].id);
  const [filter, setFilter] = React.useState('all');
  const [drawerItem, setDrawerItem] = React.useState(null);
  const site = window.SEO_SITES.find(s => s.id === siteId);
  const queue = window.SEO_QUEUE.filter(q => q.site === siteId);

  // Issues mock para o site (mistura queue + sintéticas)
  const allIssues = [
    ...queue.map(q => ({ ...q, state: 'pending' })),
    // sintéticas baseadas nos números
    ...Array.from({ length: Math.min(8, site.medium) }).map((_, i) => ({
      id: `s-${siteId}-${i}`, site: siteId,
      type: ['META_MISSING', 'H1_MULTIPLE', 'META_DUPLICATE', 'META_TOO_LONG'][i % 4],
      severity: i < 2 ? 'medium' : 'low',
      url: ['/produtos/uv', '/blog/2024', '/contactos', '/sobre', '/recursos', '/faq', '/parceiros', '/eventos'][i],
      lang: site.langs[0],
      section: ['produto', 'blog', 'institucional', 'institucional', 'recursos', 'institucional', 'institucional', 'eventos'][i],
      age: ['há 2h', 'há 4h', 'há 6h', 'há 1d', 'há 2d', 'há 3d', 'há 5d', 'há 1sem'][i],
      state: i === 1 ? 'fixing' : i === 5 ? 'fixed' : 'new',
      detail: ['Falta meta description', '3 H1 detectados', 'Meta igual a 7 páginas', 'Meta com 198 chars'][i % 4],
    })),
  ];

  const filtered = filter === 'all' ? allIssues
    : filter === 'critical' ? allIssues.filter(x => x.severity === 'critical')
    : filter === 'medium' ? allIssues.filter(x => x.severity === 'medium')
    : filter === 'low' ? allIssues.filter(x => x.severity === 'low')
    : allIssues;

  const stateLabel = { new: 'Novo', pending: 'Pendente', fixing: 'A corrigir', fixed: 'Corrigido', ignored: 'Ignorado' };
  const stateColor = { new: 'var(--text-muted)', pending: 'var(--warning)', fixing: 'var(--ai-500)', fixed: 'var(--success)', ignored: 'var(--text-dim)' };

  return (
    <>
      <div style={{ display: 'grid', gridTemplateColumns: '300px 1fr', gap: 0, height: '100%', minHeight: 0, border: '1px solid var(--border)', borderRadius: 10, overflow: 'hidden' }}>
        {/* coluna 1 · lista de sites */}
        <div className="scrollbar" style={{ borderRight: '1px solid var(--border)', overflowY: 'auto', background: 'var(--bg-sunken)' }}>
          <div style={{ padding: '12px 14px', borderBottom: '1px solid var(--border)', fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>
            5 sites
          </div>
          {window.SEO_SITES.map(s => {
            const active = s.id === siteId;
            const sc = s.score >= 80 ? 'var(--success)' : s.score >= 60 ? 'var(--warning)' : s.score >= 40 ? '#f97316' : 'var(--danger)';
            return (
              <button key={s.id} onClick={() => setSiteId(s.id)} style={{
                width: '100%', textAlign: 'left',
                padding: '12px 14px', borderBottom: '1px solid var(--border)',
                background: active ? 'var(--bg-hover)' : 'transparent',
                position: 'relative',
              }}>
                {active && <span style={{ position: 'absolute', left: 0, top: 8, bottom: 8, width: 2, background: 'var(--ai-500)' }} />}
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}>
                    <span style={{ width: 6, height: 6, borderRadius: 1, background: s.brandColor, flexShrink: 0 }} />
                    <span className="font-mono" style={{ fontSize: 11.5, fontWeight: active ? 600 : 400, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.domain}</span>
                  </div>
                  <span className="font-display" style={{ fontSize: 14, fontWeight: 600, color: sc, flexShrink: 0 }}>{s.score}</span>
                </div>
                <div style={{ display: 'flex', gap: 8, marginTop: 5, fontSize: 10, 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>
                  <span style={{ marginLeft: 'auto', color: 'var(--text-dim)' }}>{s.mode}</span>
                </div>
              </button>
            );
          })}
        </div>

        {/* coluna 2 · detalhe */}
        <div style={{ display: 'flex', flexDirection: 'column', minWidth: 0, minHeight: 0 }}>
          {/* header */}
          <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--border)', flexShrink: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 10 }}>
              <span style={{ width: 10, height: 10, borderRadius: 2, background: site.brandColor }} />
              <h2 className="font-display" style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>{site.domain}</h2>
              <span className="font-mono" style={{ fontSize: 11, padding: '2px 8px', background: 'var(--surface-muted)', borderRadius: 4, color: 'var(--text-muted)' }}>{site.cms}</span>
              <span className="font-mono" style={{ fontSize: 11, color: 'var(--text-dim)' }}>{site.langs.join(' · ')}</span>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 4, marginLeft: 'auto' }}>
                <span className="font-display" style={{ fontSize: 24, fontWeight: 600, color: site.score >= 60 ? 'var(--warning)' : 'var(--danger)' }}>{site.score}</span>
                <span style={{ fontSize: 11, color: 'var(--text-dim)' }}>/100</span>
              </div>
              <button className="btn btn-sm btn-ai"><Icon name="refresh" size={12} /> Lançar audit</button>
              <button className="btn btn-sm"><Icon name="globe" size={12} /> GSC</button>
              <button className="btn btn-sm"><Icon name="wrench" size={12} /></button>
            </div>

            {/* filtros chips */}
            <div style={{ display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap' }}>
              {[
                { id: 'all',      label: `Todos · ${allIssues.length}` },
                { id: 'critical', label: `🔴 Crítico · ${site.critical}` },
                { id: 'medium',   label: `🟡 Médio · ${site.medium}` },
                { id: 'low',      label: `🟢 Baixo · ${site.low}` },
              ].map(f => (
                <button key={f.id} onClick={() => setFilter(f.id)} style={{
                  padding: '4px 10px', borderRadius: 999, fontSize: 11,
                  fontFamily: 'var(--font-mono)',
                  background: filter === f.id ? 'var(--brand-900)' : 'var(--surface-muted)',
                  color: filter === f.id ? '#fff' : 'var(--text-muted)',
                  border: '1px solid var(--border)',
                }}>{f.label}</button>
              ))}
              <span style={{ width: 1, height: 18, background: 'var(--border)', marginInline: 4 }} />
              <button className="btn btn-xs btn-ghost"><Icon name="filter" size={11} /> tipo</button>
              <button className="btn btn-xs btn-ghost"><Icon name="filter" size={11} /> idioma</button>
              <button className="btn btn-xs btn-ghost"><Icon name="filter" size={11} /> secção</button>
              <span style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 6, padding: '4px 10px', background: 'var(--surface-muted)', borderRadius: 999, border: '1px solid var(--border)', fontSize: 11 }}>
                <Icon name="search" size={11} />
                <input placeholder="procurar URL…" style={{ background: 'transparent', border: 'none', outline: 'none', fontSize: 11, width: 120, color: 'var(--text)' }} />
              </span>
            </div>
          </div>

          {/* table */}
          <div className="scrollbar" style={{ flex: 1, overflowY: 'auto' }}>
            <div style={{
              display: 'grid', gridTemplateColumns: '24px 1fr 140px 90px 1fr 100px 110px',
              gap: 0, padding: '8px 20px', fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em', textTransform: 'uppercase',
              borderBottom: '1px solid var(--border)', background: 'var(--bg-sunken)',
              position: 'sticky', top: 0, zIndex: 1,
            }}>
              <div></div>
              <div>URL</div>
              <div>Tipo</div>
              <div>Sev.</div>
              <div>Detalhe</div>
              <div>Estado</div>
              <div style={{ textAlign: 'right' }}>Acção</div>
            </div>
            {filtered.map(it => (
              <div key={it.id}
                onClick={() => setDrawerItem(it)}
                style={{
                  display: 'grid', gridTemplateColumns: '24px 1fr 140px 90px 1fr 100px 110px',
                  gap: 0, padding: '11px 20px', alignItems: 'center',
                  borderBottom: '1px solid var(--border)',
                  fontSize: 12, cursor: 'pointer',
                }}
                onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'}
                onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
              >
                <input type="checkbox" onClick={e => e.stopPropagation()} style={{ accentColor: 'var(--ai-500)' }} />
                <div className="font-mono" style={{ fontSize: 11.5, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', paddingRight: 8 }}>{it.url}</div>
                <SeoTypeBadge type={it.type} />
                <SeoBadge severity={it.severity} mini />
                <div style={{ fontSize: 11, color: 'var(--text-muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', paddingRight: 8 }}>
                  {it.detail || (window.SEO_ISSUE_TYPES[it.type]?.label)}
                </div>
                <span className="font-mono" style={{ fontSize: 10.5, color: stateColor[it.state] }}>
                  {stateLabel[it.state] || it.state}
                </span>
                <button onClick={(e) => { e.stopPropagation(); setDrawerItem(it); }} className="btn btn-xs btn-ai" style={{ justifySelf: 'end' }}>
                  Ver fix <Icon name="arrowRight" size={10} />
                </button>
              </div>
            ))}
            {filtered.length === 0 && (
              <div style={{ padding: 40, textAlign: 'center', fontSize: 12, color: 'var(--text-muted)' }}>Sem issues neste filtro.</div>
            )}
          </div>
        </div>
      </div>

      <SeoIssueDrawer item={drawerItem} onClose={() => setDrawerItem(null)} onApprove={() => setDrawerItem(null)} onReject={() => setDrawerItem(null)} />
    </>
  );
};
window.SeoViewSites = SeoViewSites;

// ──────────────────────────────────────────────────────────────────────────
// VIEW 3 · QUEUE (Para Aprovar)
// ──────────────────────────────────────────────────────────────────────────
const SeoViewQueue = () => {
  const [groupBy, setGroupBy] = React.useState('type');
  const [activeGroup, setActiveGroup] = React.useState('all');
  const [drawerItem, setDrawerItem] = React.useState(null);
  const [removed, setRemoved] = React.useState(new Set());
  const [autoApproveLow, setAutoApproveLow] = React.useState(false);

  const all = window.SEO_QUEUE.filter(q => !removed.has(q.id));

  const groups = React.useMemo(() => {
    const g = {};
    all.forEach(it => {
      const key = groupBy === 'type' ? it.type
        : groupBy === 'site' ? it.site
        : groupBy === 'severity' ? it.severity
        : 'all';
      g[key] = (g[key] || 0) + 1;
    });
    return g;
  }, [all, groupBy]);

  const filtered = activeGroup === 'all' ? all : all.filter(it => {
    const k = groupBy === 'type' ? it.type : groupBy === 'site' ? it.site : it.severity;
    return k === activeGroup;
  });

  const handleApprove = (item) => {
    setRemoved(prev => new Set([...prev, item.id]));
    setDrawerItem(null);
  };
  const handleReject = (item) => {
    setRemoved(prev => new Set([...prev, item.id]));
    setDrawerItem(null);
  };

  return (
    <>
      <div style={{ display: 'grid', gridTemplateColumns: '240px 1fr', gap: 18, height: '100%', minHeight: 0 }}>
        {/* sidebar esquerda · agrupamento */}
        <div className="card scrollbar" style={{ padding: 12, overflowY: 'auto', alignSelf: 'start' }}>
          <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 8 }}>Agrupar por</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 4, marginBottom: 14 }}>
            {[
              { id: 'type',     label: 'Tipo' },
              { id: 'site',     label: 'Site' },
              { id: 'severity', label: 'Sev.' },
              { id: 'none',     label: 'Nada' },
            ].map(g => (
              <button key={g.id} onClick={() => { setGroupBy(g.id); setActiveGroup('all'); }} style={{
                padding: '5px 8px', fontSize: 11, borderRadius: 5,
                background: groupBy === g.id ? 'var(--brand-900)' : 'var(--surface-muted)',
                color: groupBy === g.id ? '#fff' : 'var(--text-muted)',
                border: '1px solid var(--border)',
              }}>{g.label}</button>
            ))}
          </div>

          <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 6 }}>{Object.keys(groups).length} grupos</div>
          <button onClick={() => setActiveGroup('all')} style={{
            width: '100%', textAlign: 'left',
            padding: '6px 8px', borderRadius: 5, marginBottom: 2, fontSize: 12,
            background: activeGroup === 'all' ? 'var(--bg-hover)' : 'transparent',
            color: activeGroup === 'all' ? 'var(--text)' : 'var(--text-muted)',
            display: 'flex', justifyContent: 'space-between',
          }}>
            <span style={{ fontWeight: 500 }}>Todos</span>
            <span className="font-mono" style={{ fontSize: 10.5, color: 'var(--text-dim)' }}>{all.length}</span>
          </button>
          {Object.entries(groups).sort((a, b) => b[1] - a[1]).map(([key, count]) => {
            const label = groupBy === 'site' ? window.SEO_SITES.find(s => s.id === key)?.domain
                       : groupBy === 'severity' ? seoSeverityLabel[key]
                       : key;
            return (
              <button key={key} onClick={() => setActiveGroup(key)} style={{
                width: '100%', textAlign: 'left',
                padding: '6px 8px', borderRadius: 5, marginBottom: 2,
                background: activeGroup === key ? 'var(--bg-hover)' : 'transparent',
                color: activeGroup === key ? 'var(--text)' : 'var(--text-muted)',
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                fontSize: 11.5,
                fontFamily: groupBy === 'type' ? 'var(--font-mono)' : 'inherit',
              }}>
                <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{label}</span>
                <span className="font-mono" style={{ fontSize: 10.5, color: 'var(--text-dim)', marginLeft: 8 }}>{count}</span>
              </button>
            );
          })}

          <div style={{ marginTop: 16, paddingTop: 12, borderTop: '1px solid var(--border)' }}>
            <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 11.5, color: 'var(--text-muted)', cursor: 'pointer' }}>
              <input type="checkbox" checked={autoApproveLow} onChange={e => setAutoApproveLow(e.target.checked)} style={{ accentColor: 'var(--ai-500)' }} />
              Aprovar Baixos automaticamente
            </label>
          </div>
        </div>

        {/* coluna principal · cards */}
        <div className="scrollbar" style={{ overflowY: 'auto', paddingRight: 8 }}>
          {/* topbar interna */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
            <div className="font-display" style={{ fontSize: 13, fontWeight: 600 }}>{filtered.length} fixes a aguardar</div>
            <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>· percorre com J/K · A aprova · I ignora</span>
            <span style={{ flex: 1 }} />
            <button className="btn btn-sm">Aprovar grupo actual</button>
            <button className="btn btn-sm btn-ghost"><Icon name="users" size={12} /> Atribuir a…</button>
          </div>

          {filtered.length === 0 ? (
            <div className="card" style={{ padding: 48, textAlign: 'center' }}>
              <Icon name="check" size={28} style={{ color: 'var(--success)' }} />
              <div className="font-display" style={{ fontSize: 16, fontWeight: 600, marginTop: 10 }}>Tudo arrumado.</div>
              <div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 6, lineHeight: 1.55, maxWidth: 420, marginInline: 'auto' }}>
                A Digi corrigiu os últimos 47 issues e está agora a varrer <span className="font-mono">mimaki.digidelta.es</span>. Volta dentro de 2h ou deixa em modo full-auto.
              </div>
              <div style={{ display: 'flex', gap: 8, marginTop: 14, justifyContent: 'center' }}>
                <button className="btn btn-sm btn-ai">Configurar full-auto</button>
                <button className="btn btn-sm">Lançar novo audit</button>
              </div>
            </div>
          ) : filtered.map(item => {
            const site = window.SEO_SITES.find(s => s.id === item.site);
            const def = window.SEO_ISSUE_TYPES[item.type] || {};
            return (
              <div key={item.id} className="card animate-in" style={{ padding: 16, marginBottom: 12 }}>
                {/* header */}
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10, flexWrap: 'wrap' }}>
                  <SeoBadge severity={item.severity} mini />
                  <SeoTypeBadge type={item.type} />
                  <span className="font-mono" style={{ fontSize: 11, color: 'var(--text-muted)' }}>
                    <span style={{ color: site?.brandColor, fontWeight: 600 }}>{site?.domain}</span>
                    <span style={{ color: 'var(--ai-400)' }}>{item.url}</span>
                  </span>
                  <span style={{ flex: 1 }} />
                  <span className="font-mono" style={{ fontSize: 10.5, color: 'var(--text-dim)' }}>{item.lang} · {item.section} · {item.age}</span>
                </div>

                {/* before / after */}
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 10 }}>
                  <div>
                    <div style={{ fontSize: 9.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', marginBottom: 3, letterSpacing: '0.06em' }}>ANTES</div>
                    <div className="font-mono" style={{
                      padding: '8px 10px',
                      background: 'color-mix(in oklch, var(--danger) 5%, var(--surface-muted))',
                      border: '1px solid color-mix(in oklch, var(--danger) 18%, var(--border))',
                      borderRadius: 5, fontSize: 11.5, lineHeight: 1.5, color: 'var(--text-muted)',
                    }}>{item.before}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: 9.5, color: 'var(--ai-400)', fontFamily: 'var(--font-mono)', marginBottom: 3, letterSpacing: '0.06em' }}>DEPOIS · proposta da Digi</div>
                    <div className="font-mono" style={{
                      padding: '8px 10px',
                      background: 'color-mix(in oklch, var(--ai-500) 7%, transparent)',
                      border: '1px solid color-mix(in oklch, var(--ai-500) 28%, transparent)',
                      borderRadius: 5, fontSize: 11.5, lineHeight: 1.5, color: 'var(--text)',
                    }}>{item.after}</div>
                  </div>
                </div>

                <div style={{ fontSize: 11.5, color: 'var(--text-muted)', marginBottom: 12, lineHeight: 1.5 }}>
                  <Icon name="sparkle" size={10} style={{ color: 'var(--ai-500)', verticalAlign: '-1px', marginRight: 5 }} />
                  {item.why}
                </div>

                {/* footer · acções */}
                <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
                  <button className="btn btn-sm btn-ai" onClick={() => handleApprove(item)}>
                    <Icon name="check" size={12} /> Aprovar
                  </button>
                  <button className="btn btn-sm" onClick={() => setDrawerItem(item)}>
                    <Icon name="wrench" size={11} /> Editar
                  </button>
                  <button className="btn btn-sm btn-ghost"><Icon name="refresh" size={11} /> Outra</button>
                  <button className="btn btn-sm btn-ghost" onClick={() => handleReject(item)}>
                    <Icon name="close" size={11} /> Ignorar
                  </button>
                  {item.related > 0 && (
                    <span style={{ marginLeft: 'auto', fontSize: 10.5, color: 'var(--info)', fontFamily: 'var(--font-mono)' }}>
                      <Icon name="layers" size={10} style={{ verticalAlign: '-1px', marginRight: 4 }} />
                      +{item.related} mesmo padrão
                    </span>
                  )}
                  {item.autoApplying && (
                    <span style={{ marginLeft: 'auto', fontSize: 10.5, color: 'var(--ai-400)', fontFamily: 'var(--font-mono)', display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                      <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'var(--ai-halo)', animation: 'ai-shimmer 1.4s infinite' }} />
                      A aplicar automaticamente
                    </span>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      <SeoIssueDrawer item={drawerItem} onClose={() => setDrawerItem(null)} onApprove={handleApprove} onReject={handleReject} />
    </>
  );
};
window.SeoViewQueue = SeoViewQueue;

// ──────────────────────────────────────────────────────────────────────────
// VIEW 4 · HISTÓRICO
// ──────────────────────────────────────────────────────────────────────────
const SeoViewHistory = () => {
  const typeIcon = { 'fix-bulk': '✅', 'fix-single': '✅', 'audit': '📊', 'reject': '✕', 'config': '⚙' };
  const typeColor = { 'fix-bulk': 'var(--success)', 'fix-single': 'var(--success)', 'audit': 'var(--info)', 'reject': 'var(--text-dim)', 'config': 'var(--text-muted)' };

  return (
    <div className="scrollbar" style={{ height: '100%', overflowY: 'auto', paddingRight: 8 }}>
      {/* filtros */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 16, flexWrap: 'wrap' }}>
        {['Todos os sites', 'Todos os tipos', 'Todos os autores', '7d'].map(f => (
          <button key={f} className="btn btn-sm btn-ghost" style={{ background: 'var(--surface-muted)' }}>
            {f} <Icon name="chevron" size={10} />
          </button>
        ))}
        <span style={{ flex: 1 }} />
        <button className="btn btn-sm"><Icon name="download" size={12} /> Exportar CSV</button>
      </div>

      {/* timeline */}
      <div className="card" style={{ padding: '4px 0' }}>
        {window.SEO_HISTORY.map((h, i) => (
          <div key={i} style={{
            padding: '14px 18px',
            borderTop: i === 0 ? 'none' : '1px solid var(--border)',
            display: 'grid', gridTemplateColumns: '32px 1fr auto', gap: 14, alignItems: 'flex-start',
          }}>
            <div style={{
              width: 28, height: 28, borderRadius: 6,
              background: `color-mix(in oklch, ${typeColor[h.type]} 14%, transparent)`,
              color: typeColor[h.type],
              display: 'grid', placeItems: 'center', fontSize: 13,
              border: `1px solid color-mix(in oklch, ${typeColor[h.type]} 28%, transparent)`,
              flexShrink: 0,
            }}>{typeIcon[h.type]}</div>

            <div style={{ minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, flexWrap: 'wrap' }}>
                <span className="font-mono" style={{ fontSize: 10.5, color: 'var(--text-dim)' }}>{h.ts}</span>
                <span style={{ fontSize: 10.5, color: 'var(--text-muted)' }}>·</span>
                <span style={{ fontSize: 11, color: typeColor[h.type], fontWeight: 500 }}>{h.actor}</span>
              </div>
              <div className="font-display" style={{ fontSize: 13, fontWeight: 500, marginTop: 4, color: 'var(--text)' }}>{h.title}</div>
              <div style={{ fontSize: 11.5, color: 'var(--text-muted)', marginTop: 3, lineHeight: 1.5 }}>{h.detail}</div>
            </div>

            <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
              <button className="btn btn-xs">Ver detalhe</button>
              {h.revertable && <button className="btn btn-xs btn-ghost"><Icon name="history" size={10} /> Reverter</button>}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};
window.SeoViewHistory = SeoViewHistory;

// ──────────────────────────────────────────────────────────────────────────
// VIEW 5 · CONFIGURAÇÃO
// ──────────────────────────────────────────────────────────────────────────
const SeoViewConfig = () => {
  const [preset, setPreset] = React.useState('balanced');
  const [rows, setRows] = React.useState(window.SEO_CONFIG);

  const setRowMode = (idx, mode) => {
    setRows(prev => prev.map((r, i) => i === idx ? { ...r, mode } : r));
  };

  return (
    <div className="scrollbar" style={{ height: '100%', overflowY: 'auto', paddingRight: 8, paddingBottom: 40 }}>
      {/* presets */}
      <div className="card" style={{ padding: 16, marginBottom: 16 }}>
        <div style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 8 }}>
          Presets rápidos
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
          {[
            { id: 'conservative', name: 'Conservador',  desc: 'Tudo manual · cada fix pede aprovação.' },
            { id: 'balanced',     name: 'Equilibrado',   desc: 'Baixo full-auto · Médio semi-auto · Crítico manual.', recommended: true },
            { id: 'aggressive',   name: 'Agressivo',     desc: 'Tudo full-auto excepto homepage e páginas-pilar.' },
          ].map(p => (
            <button key={p.id} onClick={() => setPreset(p.id)} style={{
              padding: 12, textAlign: 'left',
              borderRadius: 8, position: 'relative',
              background: preset === p.id ? 'color-mix(in oklch, var(--ai-500) 8%, transparent)' : 'var(--surface-muted)',
              border: '1px solid ' + (preset === p.id ? 'color-mix(in oklch, var(--ai-500) 40%, transparent)' : 'var(--border)'),
            }}>
              {p.recommended && (
                <span style={{ position: 'absolute', top: -8, right: 10, fontSize: 9, padding: '1px 6px', background: 'var(--ai-500)', color: '#fff', borderRadius: 3, fontFamily: 'var(--font-mono)', fontWeight: 600 }}>
                  RECOMENDADO
                </span>
              )}
              <div className="font-display" style={{ fontSize: 13, fontWeight: 600 }}>{p.name}</div>
              <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 4, lineHeight: 1.5 }}>{p.desc}</div>
            </button>
          ))}
        </div>
      </div>

      {/* tabela */}
      <div className="card" style={{ overflow: 'hidden' }}>
        <div style={{
          display: 'grid', gridTemplateColumns: '1.4fr 1.2fr 1.4fr 1.1fr 1.2fr',
          padding: '10px 16px', fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', textTransform: 'uppercase',
          borderBottom: '1px solid var(--border)', background: 'var(--bg-sunken)',
        }}>
          <div>Site</div>
          <div>Tipo de issue</div>
          <div>Modo</div>
          <div>Aprovador</div>
          <div>Notificação</div>
        </div>
        {rows.map((r, i) => {
          const site = window.SEO_SITES.find(s => s.id === r.siteId);
          const modeColor = r.mode === 'Full-auto' ? 'var(--ai-500)'
                         : r.mode === 'Semi-auto' ? 'var(--info)'
                         : 'var(--warning)';
          return (
            <div key={i} style={{
              display: 'grid', gridTemplateColumns: '1.4fr 1.2fr 1.4fr 1.1fr 1.2fr',
              padding: '10px 16px', alignItems: 'center', fontSize: 12,
              borderTop: i === 0 ? 'none' : '1px solid var(--border)',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ width: 6, height: 6, borderRadius: 1, background: site?.brandColor }} />
                <span className="font-mono" style={{ fontSize: 11.5 }}>{site?.domain}</span>
              </div>
              <SeoTypeBadge type={r.type} />
              <select
                value={r.mode}
                onChange={e => setRowMode(i, e.target.value)}
                style={{
                  padding: '4px 8px', fontSize: 11, fontFamily: 'var(--font-mono)',
                  background: `color-mix(in oklch, ${modeColor} 10%, transparent)`,
                  color: modeColor,
                  border: `1px solid color-mix(in oklch, ${modeColor} 30%, transparent)`,
                  borderRadius: 4, width: 'fit-content',
                }}
              >
                <option>Manual</option>
                <option>Semi-auto</option>
                <option>Full-auto</option>
              </select>
              <span style={{ fontSize: 11.5, color: r.approver === '—' ? 'var(--text-dim)' : 'var(--text-muted)' }}>{r.approver}</span>
              <span style={{ fontSize: 11, color: r.notify === '—' ? 'var(--text-dim)' : 'var(--text-muted)' }}>{r.notify}</span>
            </div>
          );
        })}
      </div>

      {/* avançado */}
      <div className="card" style={{ padding: 16, marginTop: 16 }}>
        <div style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 10 }}>
          Configuração avançada por site
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10 }}>
          {[
            { icon: 'globe',    label: 'CMS / repositório',         val: 'WordPress · Next.js · Webflow' },
            { icon: 'history',  label: 'Frequência de crawl',       val: 'Diária · Semanal · Manual' },
            { icon: 'flag',     label: 'Páginas excluídas',         val: '/campanhas/* · / (homepage)' },
            { icon: 'layers',   label: 'KB de tom por marca',       val: '6 KBs activas (mimaki, biond, decal, sensek, alldecor, digidelta)' },
            { icon: 'link',     label: 'Integração GSC',            val: '5/5 sites ligados · OAuth válido' },
            { icon: 'send',     label: 'Webhook notificação',       val: 'Slack #seo-alerts · Email F. Costa' },
          ].map(x => (
            <div key={x.label} style={{
              padding: 10, background: 'var(--surface-muted)', borderRadius: 6,
              border: '1px solid var(--border)',
              display: 'flex', alignItems: 'center', gap: 10,
            }}>
              <Icon name={x.icon} size={14} style={{ color: 'var(--text-muted)', flexShrink: 0 }} />
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 11, color: 'var(--text)', fontWeight: 500 }}>{x.label}</div>
                <div style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis' }}>{x.val}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};
window.SeoViewConfig = SeoViewConfig;
