/* SDR Humano — formação por marca e guião das campanhas activas.
   O ecrã SDR AI (supervisão da Digi) fica no sub "sdr". */

const SH_INBOUND = 'A pessoa escreveu-nos. Confirmas o BANT e marcas um dia e uma hora.';
const SH_OUTBOUND = 'A Digi contactou primeiro. Usas os passos abaixo. Dois toques mudam o ângulo; ao quarto, o ciclo fecha.';

function shEmail(userEmail) {
  return userEmail || window.currentUser?.email || '';
}

async function shApi(url, userEmail, options = {}) {
  const p = new URLSearchParams(window.location.search || '');
  const email = shEmail(userEmail);
  if (email && !p.get('email')) p.set('email', email);
  const sep = url.includes('?') ? '&' : '?';
  const res = await fetch(`${url}${sep}${p.toString()}`, {
    headers: { 'Content-Type': 'application/json' },
    ...options,
  });
  const body = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(body.error || `HTTP ${res.status}`);
  return body;
}

function shTexto(s) {
  return String(s || '').replace(/^#{1,6}\s+/gm, '').replace(/\*\*(.+?)\*\*/g, '$1').trim();
}

function rotuloCamp(c) {
  const marca = String(c?.campanha?.marca || '').trim();
  const titulo = String(c?.campanha?.titulo || 'Campanha').trim();
  if (!marca) return titulo;
  if (titulo.toLowerCase().startsWith(marca.toLowerCase())) return titulo;
  return marca + ' · ' + titulo;
}

const SH_MARCAS = new Set(['mimaki', 'biond', 'decal', 'alldecor', 'sensek', 'netscreen']);

function shMarcasNav() {
  const deDados = (window.MKT_BRANDS || []).filter(b => b.id && b.id !== 'todas').map(b => ({ id: b.id, nome: b.nome }));
  const lista = deDados.length ? deDados : [
    { id: 'mimaki', nome: 'Mimaki' }, { id: 'biond', nome: 'BIOND' }, { id: 'decal', nome: 'Decal' },
    { id: 'alldecor', nome: 'AllDecor' }, { id: 'sensek', nome: 'Sensek' }, { id: 'netscreen', nome: 'NetScreen' },
  ];
  return [{ id: 'todas', nome: 'Todas' }, ...lista.filter(b => SH_MARCAS.has(b.id))];
}

function shHash({ licao, camp, marca, produto, inicial }) {
  const q = new URLSearchParams((window.location.hash || '').replace(/^#/, ''));
  q.set('screen', 'marketing');
  q.set('sub', 'sdr-humano');
  q.delete('tab');
  if (licao) q.set('licao', licao); else q.delete('licao');
  if (camp) q.set('camp', camp); else q.delete('camp');
  if (produto) q.set('produto', produto); else q.delete('produto');
  if (inicial) q.set('inicial', inicial); else q.delete('inicial');
  if (marca && marca !== 'todas') q.set('marca', marca); else q.delete('marca');
  const next = q.toString();
  if (window.location.hash.replace(/^#/, '') !== next) window.location.hash = next;
}

function shParams() {
  try { return new URLSearchParams((window.location.hash || '').replace(/^#/, '')); } catch { return new URLSearchParams(); }
}

const shCard = { background: '#fff', border: '1px solid var(--border)', borderRadius: 10, overflow: 'hidden' };
const shTh = { textAlign: 'left', fontSize: 10, fontWeight: 600, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '.04em', padding: '8px 10px', borderBottom: '1px solid var(--border)', whiteSpace: 'nowrap', background: '#fff' };
const shTd = { fontSize: 12, padding: '10px', borderBottom: '1px solid var(--border)', verticalAlign: 'middle', color: 'var(--text)' };
const SH_CSS = '.sh-kpis{display:flex;gap:12px;flex-wrap:wrap}.sh-kpis>*{flex:1 1 140px;min-width:0}.sh-row:hover{background:#f8fafc}';

function shNota(n) {
  if (n == null || Number.isNaN(Number(n))) return '—';
  return String(Math.round(Number(n) * 10) / 10).replace('.', ',');
}

function shEstadoCamp(status) {
  const map = {
    em_activacao: 'Em activação',
    em_producao: 'Em produção',
    prompts_pendente: 'Prompts pendentes',
  };
  return map[status] || status || '—';
}

function shData(v) {
  const s = String(v || '').slice(0, 10);
  const m = s.match(/^(\d{4})-(\d{2})-(\d{2})$/);
  return m ? (m[3] + '/' + m[2] + '/' + m[1]) : '';
}

const SH_CANAL = {
  meta_ads: { label: 'Meta Ads', icon: 'simple-icons:meta' },
  facebook: { label: 'Facebook', icon: 'simple-icons:facebook' },
  instagram: { label: 'Instagram', icon: 'simple-icons:instagram' },
  linkedin: { label: 'LinkedIn', icon: 'simple-icons:linkedin' },
  linkedin_ads: { label: 'LinkedIn Ads', icon: 'simple-icons:linkedin' },
  google_ads: { label: 'Google Ads', icon: 'simple-icons:google' },
  google_ads_search: { label: 'Google Search', icon: 'simple-icons:google' },
  google_ads_display: { label: 'Google Display', icon: 'simple-icons:google' },
  whatsapp: { label: 'WhatsApp', icon: 'simple-icons:whatsapp' },
  youtube: { label: 'YouTube', icon: 'simple-icons:youtube' },
  email: { label: 'Email', icon: 'lucide:mail' },
  website: { label: 'Website', icon: 'lucide:globe' },
  site: { label: 'Website', icon: 'lucide:globe' },
  muppi_led: { label: 'Painéis LED', icon: 'lucide:monitor' },
  led: { label: 'Painéis LED', icon: 'lucide:monitor' },
};

function ShCanais({ canais }) {
  const lista = Array.isArray(canais) ? canais : [];
  if (!lista.length) return <span style={{ color: 'var(--text-dim)' }}>—</span>;
  const Icone = window.MktIcon;
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, flexWrap: 'wrap', color: 'var(--text)' }}>
      {lista.map((ch, i) => {
        const meta = SH_CANAL[ch] || { label: ch, icon: '' };
        return (
          <span key={ch + '-' + i} title={meta.label} aria-label={meta.label} style={{ display: 'inline-flex', lineHeight: 0 }}>
            {Icone && meta.icon
              ? <Icone name={meta.icon} size={16} />
              : <span style={{ fontSize: 11, lineHeight: 1 }}>{String(meta.label).slice(0, 3).toUpperCase()}</span>}
          </span>
        );
      })}
    </span>
  );
}

function shVigencia(c) {
  const v = c?.campanha?.vigencia || {};
  const a = shData(v.inicio);
  const b = shData(v.fim);
  if (a && b) return a + ' a ' + b;
  return a || b || '—';
}

function ShMenu({ items, activo }) {
  const [open, setOpen] = React.useState(false);
  const [foco, setFoco] = React.useState(-1);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!open) return undefined;
    const onClick = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('mousedown', onClick);
    document.addEventListener('keydown', onKey);
    return () => { document.removeEventListener('mousedown', onClick); document.removeEventListener('keydown', onKey); };
  }, [open]);
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button type="button" aria-label="Menu" onMouseDown={e => e.stopPropagation()} onClick={() => { setOpen(v => !v); setFoco(-1); }} style={{
        width: 30, height: 30, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        border: '1px solid ' + (open ? 'var(--ai-500)' : 'var(--border)'), borderRadius: 6,
        background: open ? 'color-mix(in oklch, var(--ai-500) 10%, #fff)' : '#fff',
        color: open ? 'var(--ai-500)' : 'var(--text)', cursor: 'pointer', padding: 0,
      }}>
        <svg width="15" height="15" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"><path d="M2.5 4h11M2.5 8h11M2.5 12h11" /></svg>
      </button>
      {open && (
        <div role="menu" style={{
          position: 'absolute', top: 'calc(100% + 6px)', right: 0, zIndex: 70,
          background: '#fff', border: '1px solid var(--border)', borderRadius: 8,
          boxShadow: '0 12px 32px rgba(17,41,84,0.14)', minWidth: 280, padding: 4,
        }}>
          {items.map((it, i) => (
            <button key={it.id} type="button" role="menuitem"
              onClick={() => { setOpen(false); it.onClick(); }}
              onMouseEnter={() => setFoco(i)} onMouseLeave={() => setFoco(-1)}
              style={{
                display: 'flex', alignItems: 'center', gap: 8, width: '100%', textAlign: 'left',
                background: foco === i ? 'color-mix(in oklch, var(--ai-500) 10%, #fff)' : 'transparent',
                color: activo === it.id || foco === i ? 'var(--ai-500)' : 'var(--text)',
                border: 'none', padding: '8px 10px', borderRadius: 6, cursor: 'pointer', fontFamily: 'inherit',
              }}>
              <span style={{ flex: 1, minWidth: 0 }}>
                <span style={{ display: 'block', fontSize: 13, fontWeight: 650 }}>{it.label}</span>
                {it.sub ? <span style={{ display: 'block', fontSize: 11, color: 'var(--text-muted)', fontWeight: 400, marginTop: 1 }}>{it.sub}</span> : null}
              </span>
              {activo === it.id ? <span style={{ color: 'var(--ai-500)' }}>✓</span> : null}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

function ShKpiStrip({ items, activo, onIr }) {
  return (
    <div className="sh-kpis">
      {items.map(k => {
        const on = activo === k.id;
        return (
          <div key={k.id} onClick={() => onIr(k.id)} style={{ background: '#fff', border: '1px solid ' + (on ? k.accent : 'var(--border)'), borderRadius: 8, padding: '12px 16px 0', cursor: 'pointer', display: 'flex', flexDirection: 'column', gap: 4, overflow: 'hidden' }}>
            <div style={{ fontSize: 9.5, fontWeight: 600, letterSpacing: '0.10em', textTransform: 'uppercase', color: on ? k.accent : 'var(--text-muted)', fontFamily: 'var(--font-mono)' }}>{k.label}</div>
            <div style={{ fontSize: 22, fontWeight: 700, fontFamily: 'var(--font-display)', color: k.accent, lineHeight: 1, paddingBottom: 10 }}>{k.value}</div>
            <div style={{ height: 3, background: 'var(--bg-sunken)', overflow: 'hidden' }}><div style={{ height: '100%', width: '100%', background: k.accent }} /></div>
          </div>
        );
      })}
    </div>
  );
}

function ShEstado({ estado }) {
  const map = {
    feito: { t: 'Feito', c: 'var(--success, #177a3d)' },
    em_estudo: { t: 'Em estudo', c: 'var(--ai-500)' },
    por_fazer: { t: 'Por fazer', c: 'var(--text-dim)' },
  };
  const x = map[estado] || map.por_fazer;
  return <span style={{ fontSize: 10, fontWeight: 650, letterSpacing: '.04em', textTransform: 'uppercase', color: x.c }}>{x.t}</span>;
}

function ShFichaChamada({ camp }) {
  const mercados = camp.playbook?.mercados || [];
  const [mercado, setMercado] = React.useState(mercados[0]?.mercado || '');
  React.useEffect(() => { setMercado(mercados[0]?.mercado || ''); }, [camp.campanha?.id]);
  const bloco = mercados.find(m => m.mercado === mercado) || mercados[0];
  const f = camp.ficha || {};
  return (
    <div style={shCard}>
      <div style={{ padding: '20px 22px 4px' }}>
        <div style={{ fontSize: 11, fontWeight: 650, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--text-muted)', fontFamily: 'var(--font-mono)' }}>Ficha de chamada</div>
        <h2 style={{ margin: '6px 0 0', fontSize: 18, fontWeight: 700, fontFamily: 'var(--font-display)', letterSpacing: '-0.01em' }}>{camp.campanha?.titulo}</h2>
        {f.pitch ? <p style={{ margin: '10px 0 0', fontSize: 14, lineHeight: 1.55 }}>{f.pitch}</p> : null}
        <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 6, fontSize: 13, lineHeight: 1.45 }}>
          <div><b>Inbound.</b> {SH_INBOUND}</div>
          <div><b>Outbound.</b> {SH_OUTBOUND}</div>
        </div>
      </div>
      {mercados.length > 1 && (
        <div style={{ display: 'flex', gap: 6, padding: '14px 22px 0' }}>
          {mercados.map(m => (
            <button key={m.mercado} type="button" onClick={() => setMercado(m.mercado)} style={{
              borderRadius: 999, border: '1px solid var(--border)', padding: '4px 10px', cursor: 'pointer', fontSize: 12,
              background: m.mercado === bloco?.mercado ? 'var(--bg-hover)' : 'transparent',
              color: 'var(--text)', fontWeight: 650,
            }}>{m.mercado}</button>
          ))}
        </div>
      )}
      <div style={{ padding: '4px 22px 20px' }}>
        {(bloco?.passos || []).map(p => (
          <div key={`${bloco?.mercado}-${p.ordem}`} style={{ paddingTop: 16 }}>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.06em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>{p.titulo}</div>
            {p.dizer ? <div style={{ fontSize: 15, lineHeight: 1.5, marginTop: 4 }}>{p.dizer}</div> : null}
            {Array.isArray(p.perguntas) && p.perguntas.length ? (
              <ol style={{ margin: '6px 0 0', paddingLeft: 18, fontSize: 14, lineHeight: 1.5 }}>
                {p.perguntas.map((q, i) => <li key={i}>{q}</li>)}
              </ol>
            ) : null}
          </div>
        ))}
        {!bloco?.passos?.length ? <div style={{ paddingTop: 16, fontSize: 14, color: 'var(--text-muted)' }}>Esta ficha não traz passos de chamada.</div> : null}
        {(f.nao_dizer || []).length ? (
          <div style={{ marginTop: 16, padding: '10px 12px', borderRadius: 10, background: 'color-mix(in oklch, var(--danger, #c2312e) 8%, var(--bg))', fontSize: 13, lineHeight: 1.45 }}>
            <b>Não dizer.</b> {f.nao_dizer.join(' · ')}
          </div>
        ) : null}
      </div>
    </div>
  );
}



function ShCategoria({ nome, aberto, onToggle, meta, nivel, children }) {
  const topo = !nivel;
  return (
    <div>
      <button type="button" onClick={onToggle} aria-expanded={aberto} style={{
        display: 'flex', alignItems: 'center', gap: 8, width: '100%', textAlign: 'left',
        border: 'none', background: 'transparent', cursor: 'pointer', color: 'inherit',
        padding: (topo ? '12px 14px 6px' : '8px 14px 4px'), paddingLeft: 14 + (nivel || 0) * 14, fontFamily: 'inherit',
      }}>
        <svg width="10" height="10" viewBox="0 0 10 10" aria-hidden="true" style={{ transform: aberto ? 'rotate(90deg)' : 'none', flex: '0 0 auto' }}>
          <path d="M3 1.5 L7.5 5 L3 8.5" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
        <span style={{ flex: 1, fontSize: topo ? 11 : 12, letterSpacing: topo ? '.08em' : 0, textTransform: topo ? 'uppercase' : 'none', fontWeight: 700 }}>{nome}</span>
        <span style={{ fontSize: 11, color: 'var(--text-muted)', fontWeight: 600 }}>{meta}</span>
      </button>
      {aberto ? <div style={{ paddingBottom: 6 }}>{children}</div> : null}
    </div>
  );
}

function ShItem({ activo, onClick, titulo, sub, extra, nivel }) {
  return (
    <button type="button" onClick={onClick} style={{
      display: 'block', width: 'calc(100% - 16px)', margin: '1px 8px', textAlign: 'left',
      border: 'none', borderRadius: 8, cursor: 'pointer', fontFamily: 'inherit', color: 'inherit',
      background: activo ? 'color-mix(in oklch, var(--ai-500) 12%, transparent)' : 'transparent',
      padding: '8px 10px 8px ' + (28 + (nivel || 0) * 14) + 'px',
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8, alignItems: 'baseline' }}>
        <span style={{ fontSize: 13, fontWeight: activo ? 700 : 600, color: activo ? 'var(--ai-500)' : 'var(--text)' }}>{titulo}</span>
        {extra}
      </div>
      {sub ? <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2, lineHeight: 1.35 }}>{sub}</div> : null}
    </button>
  );
}


function tituloDoc(nome) {
  const s = String(nome || '');
  if (/^https?:/i.test(s)) {
    try { return new URL(s).hostname.replace(/^www\./, ''); } catch { return s; }
  }
  return s.replace(/\.pdf$/i, '');
}

function tipoDoc(nome) {
  const n = String(nome || '').toLowerCase();
  if (n.includes('sales')) return 'Guia de vendas';
  if (n.includes('product')) return 'Guia de produto';
  if (/^https?:/i.test(n)) return 'Página';
  return 'Documento';
}

function slidesDe(ficha) {
  const p = ficha.produto;
  const imagens = ficha.imagens || [];
  const slides = ficha.semCapa ? [] : [{
    tipo: 'capa',
    kicker: p.marca_nome + ' · ' + p.categoria + ' · ' + p.subcategoria,
    titulo: p.nome,
    texto: p.marca === 'netscreen'
      ? 'NetScreen não se qualifica. Se a conversa for sobre este produto, encaminha para o canal dedicado. Não abras BANT nem marques demo.'
      : (imagens[0] && imagens[0].origem ? 'Fotografias de ' + imagens[0].origem + '.' : ''),
    pagina: ficha.pagina || '',
    imagem: imagens[0] || null,
  }];
  const folhas = ficha.folhas || [];
  if (folhas.length) {
    for (const folha of folhas) {
      for (const pag of folha.paginas || []) {
        slides.push({
          tipo: 'folha',
          kicker: folha.rotulo + (pag.page ? ' · pág. ' + pag.page : ''),
          titulo: tituloDoc(folha.ficheiro),
          imagem: { url: pag.url, descricao: folha.ficheiro },
        });
      }
    }
    return slides;
  }
  if (imagens.some(i => i.origem)) {
    let cursor = imagens.length > 1 ? 1 : 0;
    const usadas = new Set([0]);
    for (const doc of ficha.documentos || []) {
      for (const pag of doc.paginas || []) {
        slides.push({
          tipo: 'pagina',
          kicker: tipoDoc(doc.ficheiro) + (pag.page ? ' · pág. ' + pag.page + (doc.paginas_total ? ' de ' + doc.paginas_total : '') : ''),
          titulo: tituloDoc(doc.ficheiro),
          texto: pag.texto,
          imagem: imagens[cursor] || imagens[0] || null,
          link: /^https?:/i.test(doc.ficheiro) ? doc.ficheiro : '',
        });
        usadas.add(cursor);
        if (cursor < imagens.length - 1) cursor += 1;
      }
    }
    imagens.forEach((img, i) => {
      if (usadas.has(i)) return;
      slides.push({ tipo: 'foto', kicker: img.origem, titulo: p.nome, imagem: img });
    });
    if (slides.length === 1) slides[0].vazio = true;
    return slides;
  }
  let nImg = imagens.length > 1 ? 1 : 0;
  for (const doc of ficha.documentos || []) {
    for (const pag of doc.paginas || []) {
      slides.push({
        tipo: 'pagina',
        kicker: tipoDoc(doc.ficheiro) + (pag.page ? ' · pág. ' + pag.page + (doc.paginas_total ? ' de ' + doc.paginas_total : '') : ''),
        titulo: tituloDoc(doc.ficheiro),
        texto: pag.texto,
        imagem: imagens.length ? imagens[nImg % imagens.length] : null,
        link: /^https?:/i.test(doc.ficheiro) ? doc.ficheiro : '',
      });
      if (imagens.length > 1) nImg += 1;
    }
  }
  if (slides.length === 1 && !(ficha.documentos || []).length) {
    slides[0].vazio = true;
  }
  return slides;
}

function ShDeck({ ficha, anteriorProduto, seguinteProduto, onProduto }) {
  const slides = React.useMemo(() => slidesDe(ficha), [ficha]);
  const [indice, setIndice] = React.useState(0);
  const [partidas, setPartidas] = React.useState({});
  const slide = slides[Math.min(indice, slides.length - 1)] || slides[0];
  const noInicio = indice <= 0;
  const noFim = indice >= slides.length - 1;

  const voltar = () => {
    if (!noInicio) setIndice(i => i - 1);
    else if (anteriorProduto) onProduto(anteriorProduto);
  };
  const avancar = () => {
    if (!noFim) setIndice(i => i + 1);
    else if (seguinteProduto) onProduto(seguinteProduto);
  };

  React.useEffect(() => {
    const onKey = (e) => {
      const tag = (e.target && e.target.tagName) || '';
      if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return;
      if (e.key === 'ArrowRight') { e.preventDefault(); avancar(); }
      if (e.key === 'ArrowLeft') { e.preventDefault(); voltar(); }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  });

  const pct = slides.length ? Math.round(((indice + 1) / slides.length) * 100) : 0;
  const img = slide.imagem && !partidas[slide.imagem.url] ? slide.imagem : null;

  return (
    <div>
      <div style={{ height: 3, background: 'var(--border)' }}>
        <div style={{ width: pct + '%', height: '100%', background: 'var(--ai-500)' }} />
      </div>
      <div style={{ position: 'relative', minHeight: 360, padding: '22px 56px 8px' }}>
        <button type="button" aria-label="Slide anterior" onClick={voltar} disabled={noInicio && !anteriorProduto} style={{
          position: 'absolute', left: 12, top: '46%', width: 36, height: 36, borderRadius: '50%',
          border: '1px solid var(--border)', background: '#fff', cursor: 'pointer', fontSize: 18, lineHeight: 1,
          color: 'var(--text)', opacity: noInicio && !anteriorProduto ? 0.35 : 1,
        }}>‹</button>
        <button type="button" aria-label="Slide seguinte" onClick={avancar} disabled={noFim && !seguinteProduto} style={{
          position: 'absolute', right: 12, top: '46%', width: 36, height: 36, borderRadius: '50%',
          border: '1px solid var(--border)', background: '#fff', cursor: 'pointer', fontSize: 18, lineHeight: 1,
          color: 'var(--text)', opacity: noFim && !seguinteProduto ? 0.35 : 1,
        }}>›</button>
        {(slide.tipo === 'folha' || slide.tipo === 'foto') && img ? (
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>{slide.kicker}</div>
            <div style={{ fontSize: 13, fontWeight: 650, margin: '4px 0 10px' }}>{slide.titulo}</div>
            <img src={img.url} alt={slide.titulo} onError={() => setPartidas(p => ({ ...p, [img.url]: true }))} style={{ width: '100%', maxHeight: '68vh', objectFit: 'contain', background: '#f3f5f8', borderRadius: 12, border: '1px solid var(--border)' }} />
          </div>
        ) : null}
        {slide.tipo !== 'folha' && slide.tipo !== 'foto' ? <div className={img ? 'sh-aula' : ''} style={{ alignItems: 'center', minHeight: 300 }}>
          {img ? (
            <img src={img.url} alt={img.descricao || slide.titulo} onError={() => setPartidas(p => ({ ...p, [img.url]: true }))} style={{ width: '100%', maxHeight: 320, objectFit: 'contain', background: '#f3f5f8', borderRadius: 12, border: '1px solid var(--border)' }} />
          ) : null}
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>{slide.kicker}</div>
            <h2 style={{ margin: '6px 0 0', fontSize: slide.tipo === 'capa' ? 26 : 18, fontWeight: 700, fontFamily: 'var(--font-display)', letterSpacing: '-0.02em', lineHeight: 1.2 }}>
              {slide.link ? <a href={slide.link} target="_blank" rel="noreferrer" style={{ color: 'inherit' }}>{slide.titulo}</a> : slide.titulo}
            </h2>
            {slide.texto ? (
              <div className="scrollbar" style={{ marginTop: 14, fontSize: 15, lineHeight: 1.6, whiteSpace: 'pre-wrap', maxHeight: 340, overflowY: 'auto' }}>{slide.texto}</div>
            ) : null}
            {slide.pagina ? <a href={slide.pagina} target="_blank" rel="noreferrer" style={{ display: 'inline-block', marginTop: 12, fontSize: 13, fontWeight: 650 }}>Ver no site</a> : null}
            {slide.vazio ? <div style={{ marginTop: 14, fontSize: 14, lineHeight: 1.5, color: 'var(--text-muted)' }}>A base de conhecimento não tem um guia deste produto.</div> : null}
          </div>
        </div> : null}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, padding: '8px 22px 16px' }}>
        <button type="button" className="btn" disabled={noInicio && !anteriorProduto} onClick={voltar}>Anterior</button>
        <div style={{ textAlign: 'center', minWidth: 0 }}>
          <div style={{ fontSize: 12, fontWeight: 650 }}>{(indice + 1) + ' / ' + slides.length}</div>
          {noFim && seguinteProduto ? <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>A seguir: {seguinteProduto.nome}</div> : null}
          {noInicio && anteriorProduto ? <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>Antes: {anteriorProduto.nome}</div> : null}
        </div>
        <button type="button" className="btn btn-ai" disabled={noFim && !seguinteProduto} onClick={avancar}>Seguinte</button>
      </div>
    </div>
  );
}

function MktSdrHumanoScreen({ userEmail }) {
  const [modulos, setModulos] = React.useState(null);
  const [campanhas, setCampanhas] = React.useState(null);
  const [produtos, setProdutos] = React.useState(null);
  const [marca, setMarca] = React.useState(() => shParams().get('marca') || 'todas');
  const [vista, setVista] = React.useState('inicio');
  const [painel, setPainel] = React.useState('campanhas');
  const [superficie, setSuperficie] = React.useState('licoes');
  const [aberto, setAberto] = React.useState(null);
  const [passo, setPasso] = React.useState('conteudo');
  const [licao, setLicao] = React.useState(null);
  const [respostas, setRespostas] = React.useState({});
  const [resultado, setResultado] = React.useState(null);
  const [campId, setCampId] = React.useState('');
  const [produtoId, setProdutoId] = React.useState('');
  const [ficha, setFicha] = React.useState(null);
  const [iniciais, setIniciais] = React.useState({});
  const [erro, setErro] = React.useState('');
  const [aCarregar, setACarregar] = React.useState(false);
  const [abertas, setAbertas] = React.useState({});
  const boot = React.useRef(false);
  const pedido = React.useRef(0);
  const marcaRef = React.useRef(marca);
  const iniciaisRef = React.useRef({});

  const recarregar = React.useCallback(() => {
    return shApi('/api/marketing/sdr-humano/modulos', userEmail).then(d => {
      setModulos(d);
      return d;
    });
  }, [userEmail]);

  const abrir = React.useCallback(async (id) => {
    setVista('licao');
    setPainel('formacao');
    setPasso('conteudo');
    setAberto(id);
    setCampId('');
    setProdutoId('');
    setFicha(null);
    setResultado(null);
    setRespostas({});
    setErro('');
    const marcaLicao = SH_MARCAS.has(id) ? id : (marcaRef.current && marcaRef.current !== 'todas' ? marcaRef.current : '');
    if (SH_MARCAS.has(id)) { setMarca(id); marcaRef.current = id; }
    shHash({ licao: id, marca: marcaLicao });
    const ticket = ++pedido.current;
    setACarregar(true);
    try {
      const d = await shApi('/api/marketing/sdr-humano/modulos/' + encodeURIComponent(id) + '/estudo', userEmail, { method: 'POST', body: '{}' });
      if (ticket !== pedido.current) return;
      setLicao(d);
      recarregar().catch(() => {});
    } catch (e) {
      if (ticket === pedido.current) setErro(e.message);
    } finally {
      if (ticket === pedido.current) setACarregar(false);
    }
  }, [userEmail, recarregar]);

  const abrirCamp = React.useCallback((row) => {
    const id = row?.campanha?.id || '';
    const marcaCamp = String(row?.campanha?.marca_slug || '').toLowerCase();
    setVista('apoio');
    setCampId(String(id));
    setProdutoId('');
    setFicha(null);
    setPasso('conteudo');
    setErro('');
    if (SH_MARCAS.has(marcaCamp)) { setMarca(marcaCamp); marcaRef.current = marcaCamp; }
    shHash({ camp: id, marca: marcaCamp || marcaRef.current });
  }, []);

  const abrirProduto = React.useCallback(async (p) => {
    if (!p) return;
    setVista('produto');
    setPainel('formacao');
    setProdutoId(String(p.id));
    setAberto(null);
    setLicao(null);
    setCampId('');
    setErro('');
    setMarca(p.marca);
    marcaRef.current = p.marca;
    setAbertas(a => ({
      ...a,
      ['marca:' + p.marca]: true,
      ['cat:' + p.marca + ':' + p.categoria]: true,
      ['sub:' + p.marca + ':' + p.categoria + ':' + p.subcategoria]: true,
    }));
    shHash({ produto: p.id, marca: p.marca });
    const ticket = ++pedido.current;
    setACarregar(true);
    setFicha(null);
    try {
      const d = await shApi('/api/marketing/sdr-humano/produtos/' + encodeURIComponent(p.id), userEmail);
      if (ticket !== pedido.current) return;
      setFicha(d);
    } catch (e) {
      if (ticket === pedido.current) setErro(e.message);
    } finally {
      if (ticket === pedido.current) setACarregar(false);
    }
  }, [userEmail]);

  const abrirInicial = React.useCallback((slug) => {
    const dados = iniciaisRef.current[slug];
    if (!dados || !dados.paginas || !dados.paginas.length) return false;
    setVista('inicial');
    setPainel('formacao');
    setMarca(slug);
    marcaRef.current = slug;
    setAberto('inicial:' + slug);
    setCampId('');
    setProdutoId('');
    setLicao(null);
    setPasso('conteudo');
    setResultado(null);
    setRespostas({});
    setErro('');
    setACarregar(false);
    setFicha({
      semCapa: true,
      produto: {
        id: 'inicial-' + slug,
        nome: dados.titulo || 'Formação inicial',
        marca: slug,
        marca_nome: dados.marca_nome || slug,
        categoria: 'Formação inicial',
        subcategoria: dados.workshop || '',
      },
      folhas: [{ rotulo: 'Formação inicial', ficheiro: dados.ficheiro || '', paginas: dados.paginas }],
      imagens: [],
      documentos: [],
      pagina: '',
    });
    setAbertas(a => ({ ...a, ['marca:' + slug]: true }));
    shHash({ marca: slug, inicial: slug });
    return true;
  }, []);

  const abrirRef = React.useRef(abrir);
  const abrirCampRef = React.useRef(abrirCamp);
  const abrirProdutoRef = React.useRef(abrirProduto);
  const abrirInicialRef = React.useRef(abrirInicial);
  abrirRef.current = abrir;
  abrirCampRef.current = abrirCamp;
  abrirProdutoRef.current = abrirProduto;
  abrirInicialRef.current = abrirInicial;

  React.useEffect(() => {
    let vivo = true;
    boot.current = false;
    const h = shParams();
    (async () => {
      try {
        const [mods, camps, prods, ini] = await Promise.all([
          shApi('/api/marketing/sdr-humano/modulos', userEmail),
          shApi('/api/marketing/sdr-humano/campanhas', userEmail).catch(() => ({ rows: [] })),
          shApi('/api/marketing/sdr-humano/produtos', userEmail).catch(() => ({ produtos: [] })),
          shApi('/api/marketing/sdr-humano/formacao-inicial', userEmail).catch(() => ({})),
        ]);
        if (!vivo || boot.current) return;
        boot.current = true;
        setErro('');
        const rows = camps.rows || [];
        const listaProd = prods.produtos || [];
        const mapa = ini && ini.biond ? ini : {};
        iniciaisRef.current = mapa;
        setIniciais(mapa);
        setModulos(mods);
        setCampanhas(rows);
        setProdutos(listaProd);
        const marcaInicial = h.get('marca') || 'todas';
        setMarca(marcaInicial);
        marcaRef.current = marcaInicial;
        const produtoHash = h.get('produto') || '';
        if (produtoHash) {
          const p = listaProd.find(x => String(x.id) === String(produtoHash));
          if (p) { await abrirProdutoRef.current(p); return; }
        }
        const querApoio = h.get('tab') === 'apoio';
        const camp = h.get('camp') || '';
        if (querApoio || (camp && !h.get('licao'))) {
          const row = rows.find(c => String(c.campanha?.id) === String(camp)) || (querApoio ? rows[0] : null);
          if (row) { abrirCampRef.current(row); return; }
          if (querApoio) { setVista('apoio'); setCampId(''); return; }
        }
        const lista = mods.modulos || [];
        const licaoId = h.get('licao') || '';
        if (licaoId && lista.some(m => m.id === licaoId)) {
          const mod = lista.find(m => m.id === licaoId);
          if (mod && mod.grupo === 'O trabalho') setAbertas({ 'O trabalho': true });
          if (mod && SH_MARCAS.has(mod.id)) setAbertas({ ['marca:' + mod.id]: true });
          await abrirRef.current(licaoId);
          return;
        }
        const inicialHash = h.get('inicial') || '';
        if (inicialHash && mapa[inicialHash]) {
          abrirInicialRef.current(inicialHash);
          return;
        }
        setPainel('campanhas');
        setVista('inicio');
        setSuperficie('licoes');
        setLicao(null);
        setAberto(null);
        setAbertas(marcaInicial === 'todas' ? { 'O trabalho': true } : { ['marca:' + marcaInicial]: true });
      } catch (e) {
        if (vivo) setErro(e.message);
      }
    })();
    return () => { vivo = false; };
  }, [userEmail]);

  const verificar = async () => {
    if (!aberto) return;
    setACarregar(true);
    setErro('');
    try {
      const d = await shApi('/api/marketing/sdr-humano/modulos/' + encodeURIComponent(aberto) + '/verificar', userEmail, {
        method: 'POST',
        body: JSON.stringify({ respostas }),
      });
      setResultado(d);
      recarregar().catch(() => {});
    } catch (e) {
      setErro(e.message);
    } finally {
      setACarregar(false);
    }
  };

  const escolherMarca = (id) => {
    pedido.current += 1;
    setMarca(id);
    marcaRef.current = id;
    setAberto(null);
    setLicao(null);
    setCampId('');
    setProdutoId('');
    setFicha(null);
    setResultado(null);
    setRespostas({});
    setACarregar(false);
    setVista('inicio');
    if (painel === 'formacao') setSuperficie('licoes');
    setAbertas(id === 'todas' ? { 'O trabalho': true } : { ['marca:' + id]: true });
    shHash({ marca: id });
  };

  const licoes = modulos?.modulos || [];
  const licoesMarca = marca === 'todas' ? licoes : licoes.filter(m => m.id === marca);
  const trabalho = licoes.filter(m => m.grupo === 'O trabalho');
  const camps = (campanhas || []).filter(c => marca === 'todas' || String(c.campanha?.marca_slug || '').toLowerCase() === marca);
  const listaProdutos = (produtos || []).filter(p => marca === 'todas' || p.marca === marca);
  const marcasNav = shMarcasNav();
  const nomeMarca = marcasNav.find(b => b.id === marca)?.nome || '';
  const emEstudo = licoesMarca.filter(m => m.estado === 'em_estudo');
  const porFazer = licoesMarca.filter(m => m.estado !== 'feito' && m.estado !== 'em_estudo');
  const comNota = licoesMarca.filter(m => m.score != null && m.score !== '');
  const media = comNota.length ? comNota.reduce((s, m) => s + Number(m.score), 0) / comNota.length : null;
  const seguinte = emEstudo[0] || porFazer[0] || null;
  const feitasMarca = licoesMarca.filter(m => m.estado === 'feito').length;
  const workshopsMarca = marcasNav.filter(b => b.id !== 'todas' && (marca === 'todas' || b.id === marca) && iniciais[b.id]);
  const kpiActivo = vista === 'apoio' ? 'guioes' : vista === 'inicial' ? 'workshops' : (vista === 'inicio' ? superficie : 'licoes');
  const irSuperficie = (id) => {
    pedido.current += 1;
    setPainel('formacao');
    setSuperficie(id);
    setVista('inicio');
    setAberto(null);
    setLicao(null);
    setCampId('');
    setProdutoId('');
    setFicha(null);
    setResultado(null);
    setRespostas({});
    setACarregar(false);
    shHash({ marca });
  };
  const irPainel = (id) => {
    pedido.current += 1;
    setAberto(null);
    setLicao(null);
    setCampId('');
    setProdutoId('');
    setFicha(null);
    setResultado(null);
    setRespostas({});
    setACarregar(false);
    setVista('inicio');
    if (id === 'campanhas') setPainel('campanhas');
    else { setPainel('formacao'); setSuperficie(id); }
    shHash({ marca });
  };
  const menuActivo = (vista === 'licao' || vista === 'produto') ? 'licoes'
    : vista === 'inicial' ? 'workshops'
      : vista === 'apoio' ? (painel === 'formacao' ? 'guioes' : 'campanhas')
        : (painel === 'campanhas' ? 'campanhas' : superficie);
  const menus = [
    { id: 'campanhas', label: 'Campanhas', sub: 'Campanhas no ar para qualificar e prospectar' },
    { id: 'licoes', label: 'Lições', sub: 'O trabalho, a marca e os produtos' },
    { id: 'estudo', label: 'Em estudo', sub: 'Lições que ficaram a meio' },
    { id: 'nota', label: 'Nota', sub: 'Verificação de cada lição' },
    { id: 'workshops', label: 'Workshops', sub: 'Formação inicial de Biond e AllDecor' },
    { id: 'guioes', label: 'Guiões', sub: 'Ficha de chamada das campanhas no ar' },
  ];
  const toggle = (nome) => setAbertas(a => ({ ...a, [nome]: !a[nome] }));
  const noConteudo = vista === 'licao' && passo === 'conteudo';
  const naVerificacao = vista === 'licao' && passo === 'verificacao';
  const fila = [
    ...trabalho.map(m => ({ tipo: 'licao', id: m.id })),
    ...camps.map(c => ({ tipo: 'camp', id: String(c.campanha?.id || ''), row: c })),
  ];
  const pos = fila.findIndex(x => (vista === 'licao' ? x.tipo === 'licao' && x.id === aberto : x.tipo === 'camp' && x.id === String(campId)));
  const anteriorItem = pos > 0 ? fila[pos - 1] : null;
  const seguinteItem = pos >= 0 && pos < fila.length - 1 ? fila[pos + 1] : null;
  const ir = (item) => {
    if (!item) return;
    if (item.tipo === 'licao') abrir(item.id);
    else abrirCamp(item.row);
  };
  const camp = (campanhas || []).find(c => String(c.campanha?.id) === String(campId)) || null;
  const vizinhoProduto = (delta) => {
    if (!ficha?.produto) return null;
    const seq = (produtos || []).filter(p => p.marca === ficha.produto.marca);
    const i = seq.findIndex(p => String(p.id) === String(ficha.produto.id));
    if (i < 0) return null;
    return seq[i + delta] || null;
  };

  const gruposDe = (lista) => {
    const cats = [];
    for (const p of lista) {
      let c = cats.find(x => x.nome === p.categoria);
      if (!c) { c = { nome: p.categoria, subs: [] }; cats.push(c); }
      let s = c.subs.find(x => x.nome === p.subcategoria);
      if (!s) { s = { nome: p.subcategoria, itens: [] }; c.subs.push(s); }
      s.itens.push(p);
    }
    return cats;
  };

  const blocoProdutos = (lista, slug, dentro) => gruposDe(lista).map(c => {
    const n = c.subs.reduce((acc, s) => acc + s.itens.length, 0);
    const kCat = 'cat:' + slug + ':' + c.nome;
    return (
      <ShCategoria key={kCat} nome={c.nome} nivel={dentro ? 1 : 0} aberto={abertas[kCat] === true} meta={String(n)} onToggle={() => toggle(kCat)}>
        {c.subs.map(s => {
          const kSub = 'sub:' + slug + ':' + c.nome + ':' + s.nome;
          return (
            <ShCategoria key={kSub} nome={s.nome} nivel={dentro ? 2 : 1} aberto={abertas[kSub] === true} meta={String(s.itens.length)} onToggle={() => toggle(kSub)}>
              {s.itens.map(p => (
                <ShItem key={p.id} nivel={dentro ? 2 : 1} titulo={p.nome} activo={vista === 'produto' && String(produtoId) === String(p.id)} onClick={() => abrirProduto(p)} />
              ))}
            </ShCategoria>
          );
        })}
      </ShCategoria>
    );
  });

  const tabMarca = (b) => {
    const active = b.id === marca;
    return (
      <button key={b.id} type="button" onClick={() => escolherMarca(b.id)} style={{
        background: 'none', border: 'none', outline: 'none',
        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)', letterSpacing: '.01em',
        padding: '10px 18px 12px', cursor: 'pointer', whiteSpace: 'nowrap',
      }}>{b.nome}</button>
    );
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', minHeight: 0, background: 'var(--bg)' }}>
      <style>{SH_CSS}</style>
      <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 · APOIO À CAMPANHA
        </div>
        <h1 style={{ margin: 0, fontSize: 21, fontWeight: 700, color: 'var(--text)', fontFamily: 'var(--font-display)', letterSpacing: '-0.01em', lineHeight: 1.2 }}>
          SDR Suporte
        </h1>
        <div style={{ height: 1, background: 'var(--border)', margin: '16px -40px 0' }} />
        <div style={{ display: 'flex', gap: 0, overflowX: 'auto' }}>{marcasNav.map(tabMarca)}</div>
      </div>

      <div className="scrollbar" style={{ overflowY: 'auto', flex: 1, minHeight: 0, padding: '28px 40px 64px', background: 'var(--bg)', display: 'flex', flexDirection: 'column', gap: 18 }}>
        {erro ? <div style={{ padding: '10px 12px', borderRadius: 10, background: 'color-mix(in oklch, var(--danger, #c2312e) 10%, var(--bg-elev))', color: 'var(--danger, #c2312e)', fontSize: 13 }}>{erro}</div> : null}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
          <div style={{ fontSize: 13, color: 'var(--text-muted)' }}>
            {painel === 'campanhas' && vista === 'inicio'
              ? (campanhas ? (camps.length + (camps.length === 1 ? ' campanha no ar' : ' campanhas no ar')) : 'A ler campanhas…')
              : (painel === 'formacao' && vista === 'inicio' ? (seguinte ? ('A seguir: ' + seguinte.titulo) : 'As lições deste filtro estão feitas.') : '')}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginLeft: 'auto' }}>
            {painel === 'formacao' && vista === 'inicio' ? (
              <button type="button" className="btn btn-ai" disabled={!seguinte} onClick={() => seguinte && abrir(seguinte.id)}>Continuar</button>
            ) : null}
            <ShMenu activo={menuActivo} items={menus.map(t => ({ ...t, onClick: () => irPainel(t.id) }))} />
          </div>
        </div>
        {painel === 'formacao' ? <ShKpiStrip
          activo={kpiActivo}
          onIr={irSuperficie}
          items={[
            { id: 'licoes', label: 'Lições', value: licoesMarca.length ? (feitasMarca + '/' + licoesMarca.length) : '…', accent: '#3859D0' },
            { id: 'estudo', label: 'Em estudo', value: String(emEstudo.length), accent: '#7c3aed' },
            { id: 'nota', label: 'Nota', value: shNota(media), accent: '#b45309' },
            { id: 'workshops', label: 'Workshops', value: String(workshopsMarca.length), accent: '#0891b2' },
            { id: 'guioes', label: 'Guiões', value: campanhas ? String(camps.length) : '…', accent: '#15803d' },
          ]}
        /> : null}
        {painel === 'campanhas' && vista === 'inicio' && (
          <div style={shCard}>
            {!campanhas ? <div style={{ padding: 22, fontSize: 14, color: 'var(--text-muted)' }}>A ler campanhas…</div> : null}
            {campanhas && !camps.length ? <div style={{ padding: 22, fontSize: 14, color: 'var(--text-muted)' }}>Sem campanha com briefing aprovado neste filtro.</div> : null}
            {camps.length ? (
              <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                <thead style={{ background: '#fff' }}>
                  <tr>
                    {['Marca', 'Campanha', 'Estado', 'Vigência', 'Canais'].map(h => (
                      <th key={h} style={shTh}>{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {camps.map(c => (
                    <tr key={c.campanha.id} className="sh-row" onClick={() => abrirCamp(c)} style={{ cursor: 'pointer' }}>
                      <td style={shTd}>{c.campanha.marca || '—'}</td>
                      <td style={{ ...shTd, fontWeight: 650 }}>{c.campanha.titulo}</td>
                      <td style={shTd}>{shEstadoCamp(c.campanha.status)}</td>
                      <td style={{ ...shTd, whiteSpace: 'nowrap' }}>{shVigencia(c)}</td>
                      <td style={shTd}><ShCanais canais={c.canais} /></td>
                    </tr>
                  ))}
                </tbody>
              </table>
            ) : null}
          </div>
        )}
        {painel === 'formacao' && vista === 'inicio' && superficie === 'licoes' && (
          <div style={shCard}>
            {!modulos ? <div style={{ padding: 18, fontSize: 13, color: 'var(--text-muted)' }}>A carregar o curso…</div> : (
              <div style={{ padding: '4px 0 10px' }}>
                {marca === 'todas' ? (
                  <ShCategoria nome="O trabalho" aberto={abertas['O trabalho'] === true} onToggle={() => toggle('O trabalho')} meta={trabalho.filter(m => m.estado === 'feito').length + '/' + trabalho.length}>
                    {trabalho.map(m => (
                      <ShItem key={m.id} onClick={() => abrir(m.id)} titulo={m.titulo} sub={m.resumo} extra={<ShEstado estado={m.estado} />} />
                    ))}
                  </ShCategoria>
                ) : null}
                {marca !== 'todas' && iniciais[marca] ? <ShItem titulo="Formação inicial" sub={iniciais[marca].resumo} onClick={() => abrirInicial(marca)} /> : null}
                {marca !== 'todas' && licoes.some(m => m.id === marca) ? (
                  <ShItem titulo="A marca" sub={licoes.find(m => m.id === marca)?.resumo} extra={<ShEstado estado={licoes.find(m => m.id === marca)?.estado} />} onClick={() => abrir(marca)} />
                ) : null}
                {marca !== 'todas' ? blocoProdutos(listaProdutos, marca, false) : null}
                {marca === 'todas' ? marcasNav.filter(b => b.id !== 'todas').map(b => {
                  const lista = (produtos || []).filter(p => p.marca === b.id);
                  const k = 'marca:' + b.id;
                  const mod = licoes.find(m => m.id === b.id);
                  return (
                    <ShCategoria key={b.id} nome={b.nome} aberto={abertas[k] === true} onToggle={() => toggle(k)} meta={produtos ? String(lista.length) : '…'}>
                      {iniciais[b.id] ? <ShItem nivel={1} titulo="Formação inicial" sub={iniciais[b.id].resumo} onClick={() => abrirInicial(b.id)} /> : null}
                      {mod ? <ShItem nivel={1} titulo="A marca" sub={mod.resumo} extra={<ShEstado estado={mod.estado} />} onClick={() => abrir(b.id)} /> : null}
                      {blocoProdutos(lista, b.id, true)}
                    </ShCategoria>
                  );
                }) : null}
              </div>
            )}
          </div>
        )}
        {painel === 'formacao' && vista === 'inicio' && superficie === 'estudo' && (
          <div style={shCard}>
            <div style={{ padding: '4px 0 10px' }}>
              {emEstudo.length ? emEstudo.map(m => (
                <ShItem key={m.id} onClick={() => abrir(m.id)} titulo={m.titulo} sub={m.resumo} extra={<ShEstado estado={m.estado} />} />
              )) : <div style={{ padding: 22, fontSize: 14, color: 'var(--text-muted)' }}>Nenhuma lição em estudo.</div>}
            </div>
          </div>
        )}
        {painel === 'formacao' && vista === 'inicio' && superficie === 'nota' && (
          <div style={shCard}>
            <div style={{ padding: '4px 0 10px' }}>
              {licoesMarca.length ? licoesMarca.map(m => (
                <ShItem key={m.id} onClick={() => abrir(m.id)} titulo={m.titulo} sub={m.score != null && m.score !== '' ? ('Nota ' + m.score + ' de 5') : 'Ainda sem verificação'} extra={<ShEstado estado={m.estado} />} />
              )) : <div style={{ padding: 22, fontSize: 14, color: 'var(--text-muted)' }}>Ainda sem verificação.</div>}
            </div>
          </div>
        )}
        {painel === 'formacao' && vista === 'inicio' && superficie === 'workshops' && (
          <div style={shCard}>
            <div style={{ padding: '4px 0 10px' }}>
              {workshopsMarca.length ? workshopsMarca.map(b => (
                <ShItem key={b.id} onClick={() => abrirInicial(b.id)} titulo={b.nome} sub={((iniciais[b.id].paginas || []).length) + ' slides. ' + (iniciais[b.id].resumo || '')} />
              )) : <div style={{ padding: 22, fontSize: 14, color: 'var(--text-muted)' }}>Esta marca ainda não tem workshop.</div>}
            </div>
          </div>
        )}
        {painel === 'formacao' && vista === 'inicio' && superficie === 'guioes' && (
          <div style={shCard}>
            <div style={{ padding: '4px 0 10px' }}>
              {!campanhas ? <div style={{ padding: 22, fontSize: 14, color: 'var(--text-muted)' }}>A ler campanhas…</div> : null}
              {campanhas && !camps.length ? <div style={{ padding: 22, fontSize: 14, color: 'var(--text-muted)' }}>Sem campanha activa</div> : null}
              {camps.map(c => (
                <ShItem key={c.campanha.id} onClick={() => abrirCamp(c)} titulo={rotuloCamp(c)} />
              ))}
            </div>
          </div>
        )}

        {vista !== 'inicio' && (
          <div>
            {vista === 'apoio' && (
              <div>
                <button type="button" onClick={() => irPainel(painel === 'formacao' ? 'guioes' : 'campanhas')} style={{ background: 'none', border: 'none', padding: 0, marginBottom: 12, cursor: 'pointer', color: 'var(--ai-500)', fontSize: 13, fontWeight: 650, fontFamily: 'inherit' }}>Campanhas</button>
                {campanhas && !camp ? (
                  <div style={{ ...shCard, padding: 22, fontSize: 14, lineHeight: 1.5 }}>
                    Não há campanhas com ficha activa. O guião aparece aqui quando uma campanha está activa para a Digi.
                  </div>
                ) : null}
                {camp ? <ShFichaChamada camp={camp} /> : null}
                <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, marginTop: 14 }}>
                  <button type="button" className="btn" disabled={!anteriorItem} onClick={() => ir(anteriorItem)}>Anterior</button>
                  <button type="button" className="btn btn-ai" disabled={!seguinteItem} onClick={() => ir(seguinteItem)}>Seguinte</button>
                </div>
              </div>
            )}

            {(vista === 'produto' || vista === 'inicial') && (
              <div style={shCard}>
                {!ficha ? (
                  <div style={{ padding: 28, color: 'var(--text-muted)', fontSize: 13 }}>{aCarregar ? 'A abrir o produto…' : 'Escolhe um produto no índice.'}</div>
                ) : (
                  <ShDeck
                    key={ficha.produto.id}
                    ficha={ficha}
                    anteriorProduto={vizinhoProduto(-1)}
                    seguinteProduto={vizinhoProduto(1)}
                    onProduto={abrirProduto}
                  />
                )}
              </div>
            )}

            {vista === 'licao' && (
              <div style={shCard}>
                {!licao ? (
                  <div style={{ padding: 28, color: 'var(--text-muted)', fontSize: 13 }}>
                    {aCarregar ? 'A preparar a lição…' : (marca === 'todas' ? 'Escolhe uma categoria no índice.' : ('Escolhe uma categoria e um produto de ' + nomeMarca + '.'))}
                  </div>
                ) : (
                  <div style={{ padding: '18px 0 8px' }}>
                    <div style={{ padding: '0 22px 14px' }}>
                      <h2 style={{ margin: 0, fontSize: 20, fontWeight: 700, fontFamily: 'var(--font-display)', letterSpacing: '-0.01em' }}>{licao.titulo}</h2>
                    </div>
                    <div style={{ padding: '0 22px 8px' }}>
                      <div style={{ minWidth: 0 }}>
                        <div style={{ display: 'flex', gap: 6, marginBottom: 14 }}>
                          <button type="button" onClick={() => setPasso('conteudo')} style={{
                            border: 'none', cursor: 'pointer', fontFamily: 'inherit', borderRadius: 999, padding: '6px 12px', fontSize: 12, fontWeight: 700,
                            background: noConteudo ? 'color-mix(in oklch, var(--ai-500) 14%, transparent)' : 'transparent',
                            color: noConteudo ? 'var(--ai-500)' : 'var(--text-muted)',
                          }}>1. Conteúdo</button>
                          <button type="button" onClick={() => setPasso('verificacao')} style={{
                            border: 'none', cursor: 'pointer', fontFamily: 'inherit', borderRadius: 999, padding: '6px 12px', fontSize: 12, fontWeight: 700,
                            background: naVerificacao ? 'color-mix(in oklch, var(--ai-500) 14%, transparent)' : 'transparent',
                            color: naVerificacao ? 'var(--ai-500)' : 'var(--text-muted)',
                          }}>2. Verificação</button>
                        </div>
                        {noConteudo ? (
                          <div style={{ fontSize: 14, lineHeight: 1.65, whiteSpace: 'pre-wrap' }}>{aCarregar && !licao.estudo_md ? 'A preparar a lição…' : shTexto(licao.estudo_md)}</div>
                        ) : (
                          <div>
                            {(licao.perguntas || []).map((p, i) => {
                              const corr = (resultado?.correccao || []).find(c => c.id === p.id);
                              return (
                                <fieldset key={p.id} style={{ border: 'none', margin: '0 0 14px', padding: 0 }}>
                                  <legend style={{ fontSize: 13, fontWeight: 650, marginBottom: 6 }}>{(i + 1) + '. ' + p.pergunta}</legend>
                                  {p.opcoes.map((op, oi) => (
                                    <label key={oi} style={{ display: 'flex', gap: 8, alignItems: 'flex-start', fontSize: 13, lineHeight: 1.4, marginBottom: 4, cursor: 'pointer' }}>
                                      <input type="radio" name={p.id} checked={Number(respostas[p.id]) === oi} onChange={() => setRespostas(r => ({ ...r, [p.id]: oi }))} />
                                      <span>{op}</span>
                                    </label>
                                  ))}
                                  {corr ? <div style={{ fontSize: 12, marginTop: 4, color: corr.acertou ? 'var(--success, #177a3d)' : 'var(--danger, #c2312e)' }}>{corr.acertou ? 'Certa.' : ('A resposta é: ' + corr.resposta)}</div> : null}
                                </fieldset>
                              );
                            })}
                            <button type="button" className="btn btn-ai" disabled={aCarregar} onClick={verificar}>Verificar</button>
                            {resultado ? <span style={{ marginLeft: 12, fontSize: 13 }}>{resultado.certas + ' de ' + resultado.total + '. ' + (resultado.feito ? 'Lição feita.' : ('Faltam respostas. Precisas de ' + resultado.nota_minima + '.'))}</span> : null}
                          </div>
                        )}
                      </div>
                    </div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, padding: '16px 22px 14px' }}>
                      <button type="button" className="btn" disabled={noConteudo ? !anteriorItem : false} onClick={() => { if (naVerificacao) setPasso('conteudo'); else ir(anteriorItem); }}>Anterior</button>
                      {noConteudo
                        ? <button type="button" className="btn btn-ai" onClick={() => setPasso('verificacao')}>Verificação</button>
                        : <button type="button" className="btn btn-ai" disabled={!seguinteItem} onClick={() => ir(seguinteItem)}>Seguinte</button>}
                    </div>
                  </div>
                )}
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

window.MktSdrHumanoScreen = MktSdrHumanoScreen;
