// src/screen-soporte.jsx — 2026-10-18.
//  · «Reportar un problema» (#812): desde el menú Ayuda, desde un error en pantalla (con el error ya
//    llenado) y desde Ajustes › Ayuda y soporte. El agente VE lo que se manda antes de enviar. Nada de la
//    cartera sale: sólo lo que escribe y la información técnica (versión, sistema, pantalla, último error).
//    Sin internet, queda en cola y sale solo. «Mis reportes» con folio y estado: /ajustes/reportes.
//  · «Recomienda Piixi a un colega»: un botón abre WhatsApp con el mensaje y la liga; sólo se cuenta que se
//    usó. En la beta, la liga cae a la LISTA DE ESPERA (/espera) que aprueba el equipo de Piixi, y el aviso
//    de aprobación le llega por correo (/espera/aviso). Sin códigos personales ni logros.
// Estado vivo: AxReporte y AxRecomienda; el menú Ayuda (barra de arriba), Ajustes, Inicio y el panel «Simular».
// Datos sintéticos.

const RPT_ALFA = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
const RPT_ESTADOS = {
  en_cola:  { l: 'En cola', tono: 'warm', texto: 'Guardado en esta computadora. Se manda solo en cuanto haya internet; no tienes que hacer nada.' },
  enviado:  { l: 'Enviado', tono: 'info', texto: 'Salió de tu computadora; en un momento nos llega.' },
  recibido: { l: 'Recibido', tono: 'info', texto: 'Nos llegó. Lo revisamos en orden de llegada.' },
  revision: { l: 'En revisión', tono: 'warm', texto: 'Lo estamos revisando. Si necesitamos algo más, te escribimos al correo de tu cuenta.' },
  resuelto: { l: 'Resuelto', tono: 'accent', texto: 'Lo arreglamos en Piixi 0.3.1. Actualiza desde Ayuda › Buscar actualizaciones.' },
};
const RPT_ERROR_DEMO = { codigo: 'UDEE-PDF-031', mensaje: 'No se pudo leer el archivo: la regla de la aseguradora no reconoce este formato', pantalla: 'Importar', archivo: 'poliza-autos-0004.pdf' };

function rptFolio(offset, sufijo) { let s = sufijo || ''; while (s.length < 4) s += RPT_ALFA[Math.floor(Math.random() * RPT_ALFA.length)]; return 'R-' + nbYMD(offset || 0, '') + '-' + s; }
// RFC (persona física/moral) y CURP: se tachan antes de mandar
function rptTachar(t) {
  return (t || '')
    .replace(/\b[A-ZÑ&]{4}\d{6}[HM][A-Z]{5}[A-Z0-9]\d\b/gi, '[CURP quitada]')
    .replace(/\b[A-ZÑ&]{3,4}\d{6}[A-Z0-9]{3}\b/gi, '[RFC quitado]');
}
function rptPantalla(path) {
  const p = (path || '').split('?')[0];
  if (p.startsWith('/ajustes/reportes')) return 'Ajustes › Mis reportes';
  if (p.startsWith('/ajustes/nube')) return 'Ajustes › Sincronizar por tu nube';
  if (p.startsWith('/ajustes/respaldo')) return 'Ajustes › Respaldo de tu cartera';
  if (p.startsWith('/polizas/')) return 'Ficha de póliza';
  if (p.startsWith('/clientes/')) return 'Ficha de persona';
  const t = typeof SCREEN_TITLE !== 'undefined' ? SCREEN_TITLE : {};
  for (const k of Object.keys(t).sort((a, b) => b.length - a.length)) if (p === k || p.startsWith(k + '/')) return t[k];
  return 'Inicio';
}
function rptUsoApagado() { return typeof CTA_PRIV !== 'undefined' && CTA_PRIV.decision === 'ahora_no'; }

// ─────────────────────────────────────────────────────────────
// ESTADO · Reportar un problema
// ─────────────────────────────────────────────────────────────
const AxReporte = (function () {
  const subs = new Set();
  let s = null;
  function inicial() {
    return {
      menu: false,             // menú Ayuda abierto
      abierto: false,          // diálogo abierto
      desde: '/inicio',        // la pantalla donde estaba al abrirlo
      error: null,             // el error de pantalla que ya va llenado
      descripcion: '',
      incluirDiag: null,       // null = lo que diga qDiag
      captura: false,
      verTodo: false,
      enviando: false,
      resultado: null,         // { folio, cola }
      internet: true,
      errorEnPantalla: null,   // el aviso de error que se ve en la pantalla
      reportes: [
        { folio: rptFolio(-2, 'M4PX'), fecha: rpFecha(-2, 0), resumen: 'La cobranza de una póliza no se actualizó después de cargar el portal', estado: 'revision' },
        { folio: rptFolio(-6, '7K2Q'), fecha: rpFecha(-6, 0), resumen: 'Al abrir una ficha de persona se quedaba en blanco', estado: 'resuelto' },
      ],
      qContenedor: 'A',        // A diálogo encima de donde estás · B pantalla aparte en Ajustes
      qCaptura: 'A',           // A sin captura (cero datos de clientes) · B captura opcional, se ve y se quita
      qDiag: 'A',              // A la información técnica va marcada · B va desmarcada
    };
  }
  function emit() { s = Object.assign({}, s); subs.forEach((f) => f()); }
  function asegurar() { if (!s) s = inicial(); }
  function toast(t) { if (window.__nbToast) window.__nbToast(t); }
  function avanzar(folio, a, b, ms) {
    setTimeout(() => {
      s.reportes = s.reportes.map((r) => (r.folio === folio && r.estado === a ? Object.assign({}, r, { estado: b }) : r));
      emit();
      if (b === 'recibido') toast({ kind: 'success', title: 'Tu reporte nos llegó', message: folio + ' · lo revisamos en orden de llegada.' });
    }, ms);
  }
  const api = {
    get() { asegurar(); return s; },
    subscribe(f) { subs.add(f); return () => subs.delete(f); },
    set(p) { asegurar(); Object.assign(s, p); emit(); },
    diag() { asegurar(); return s.incluirDiag == null ? s.qDiag === 'A' : s.incluirDiag; },
    abrir(opc) {
      asegurar();
      const desde = (window.location.hash || '#/inicio').slice(1);
      Object.assign(s, { menu: false, desde: desde.startsWith('/ajustes/reportes') ? s.desde : desde, error: (opc && opc.error) || null,
        descripcion: (opc && opc.error) ? 'Estaba cargando un PDF en Importar y salió el error «' + opc.error.mensaje + '».' : '',
        incluirDiag: null, captura: false, verTodo: false, enviando: false, resultado: null, errorEnPantalla: null });
      if (s.qContenedor === 'B') { s.abierto = false; emit(); window.location.hash = '/ajustes/reportes?nuevo=1'; return; }
      s.abierto = true; emit();
    },
    cerrar() { api.set({ abierto: false, resultado: null }); },
    enviar() {
      asegurar();
      if (!s.descripcion.trim() || s.enviando) return;
      s.enviando = true; emit();
      setTimeout(() => {
        const folio = rptFolio();
        const cola = !s.internet;
        s.reportes = [{ folio, fecha: 'Hoy', resumen: rptTachar(s.descripcion).slice(0, 110), estado: cola ? 'en_cola' : 'enviado' }].concat(s.reportes);
        s.enviando = false; s.resultado = { folio, cola };
        emit();
        if (!cola) avanzar(folio, 'enviado', 'recibido', 4000);
      }, 900);
    },
    volvioInternet() {
      asegurar();
      s.internet = true; emit();
      const enCola = s.reportes.filter((r) => r.estado === 'en_cola');
      enCola.forEach((r, i) => { avanzar(r.folio, 'en_cola', 'enviado', 700 + i * 300); avanzar(r.folio, 'enviado', 'recibido', 3200 + i * 300); });
      if (enCola.length) toast({ kind: 'info', title: 'Volvió internet', message: enCola.length === 1 ? 'Mandando el reporte que estaba en cola…' : 'Mandando los ' + enCola.length + ' reportes en cola…' });
    },
    simularError() { api.set({ errorEnPantalla: Object.assign({}, RPT_ERROR_DEMO) }); },
    avanzarRevision() {
      asegurar();
      const r = s.reportes.find((x) => x.estado === 'recibido');
      if (!r) return;
      api.set({ reportes: s.reportes.map((x) => (x.folio === r.folio ? Object.assign({}, x, { estado: 'revision' }) : x)) });
    },
  };
  return api;
})();
function useReporte() {
  const [, force] = useState(0);
  useEffect(() => AxReporte.subscribe(() => force((x) => x + 1)), []);
  return AxReporte.get();
}

// ─────────────────────────────────────────────────────────────
// ESTADO · Recomienda Piixi
// ─────────────────────────────────────────────────────────────
const RCM_LIGA = 'https://piixi.madpanda.mx/descarga';
const AxRecomienda = (function () {
  const subs = new Set();
  let s = null;
  function inicial() {
    return {
      abierto: false, whatsapp: false, chat: null, usos: 0, ocultaInicio: false,
      espera: { paso: 'form', correo: '', cedula: '', aviso: false },
      aprobado: false,
      qUbicacion: 'A',         // A menú Ayuda · B tarjeta en Inicio
      qBeta: 'A',              // A el mensaje dice que hay lista de espera · B sólo «descárgalo aquí»
    };
  }
  function emit() { s = Object.assign({}, s); subs.forEach((f) => f()); }
  function asegurar() { if (!s) s = inicial(); }
  const api = {
    get() { asegurar(); return s; },
    subscribe(f) { subs.add(f); return () => subs.delete(f); },
    set(p) { asegurar(); Object.assign(s, p); emit(); },
    mensaje() {
      asegurar();
      const base = 'Hola. Te recomiendo Piixi: carga tu cartera desde los portales de las aseguradoras y te ayuda con la cobranza y las renovaciones. Es gratuito.';
      return s.qBeta === 'A'
        ? base + ' Ahorita está en beta: te anotas en la liga y te avisan por correo cuando haya lugar.\n' + RCM_LIGA
        : base + ' Descárgalo aquí:\n' + RCM_LIGA;
    },
    abrir() { if (AxReporte.get().menu) AxReporte.set({ menu: false }); api.set({ abierto: true, whatsapp: false, chat: null }); },
    mandado() {
      asegurar();
      s.usos += 1; s.abierto = false; s.whatsapp = false; emit();
      if (window.__nbToast) window.__nbToast({ kind: 'success', title: 'Listo, ya se lo mandaste', message: 'Gracias por recomendar Piixi. Cuando abra la liga, se anota en la lista de espera.' });
    },
    anotar(correo, cedula) { asegurar(); s.espera = { paso: 'anotado', correo, cedula, aviso: true }; emit(); },
    reiniciarEspera() { api.set({ espera: { paso: 'form', correo: '', cedula: '', aviso: false }, aprobado: false }); },
  };
  return api;
})();
function useRecomienda() {
  const [, force] = useState(0);
  useEffect(() => AxRecomienda.subscribe(() => force((x) => x + 1)), []);
  return AxRecomienda.get();
}

// ─────────────────────────────────────────────────────────────
// MENÚ AYUDA (botón «?» de la barra de arriba)
// ─────────────────────────────────────────────────────────────
function AyudaItem({ onClick, children, sub, dataS }) {
  return (
    <button type="button" data-s={dataS} onClick={onClick} style={{
      appearance: 'none', border: 0, background: 'transparent', width: '100%', textAlign: 'left', cursor: 'default',
      padding: '8px 12px', borderRadius: 6, color: 'var(--ax-fg-strong)', fontSize: 13, display: 'flex', flexDirection: 'column', gap: 2,
    }}
      onMouseEnter={(e) => e.currentTarget.style.background = 'var(--ax-bg-3)'}
      onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
      <span>{children}</span>
      {sub ? <span style={{ fontSize: 11.5, color: 'var(--ax-fg-muted)' }}>{sub}</span> : null}
    </button>
  );
}
function AyudaBoton() {
  const r = useReporte();
  const rc = useRecomienda();
  const toast = (m) => window.__nbToast && window.__nbToast({ kind: 'info', message: m });
  return (
    <div style={{ position: 'relative' }}>
      <button className="ax-btn ax-btn--tertiary" data-s="ayuda" style={{ height: 30, width: 30, padding: 0, background: r.menu ? 'var(--ax-bg-3)' : undefined }} title="Ayuda" onClick={() => AxReporte.set({ menu: !r.menu })}>
        <AxIcon name="help" size={14}/>
      </button>
      {r.menu ? (
        <>
          <div onClick={() => AxReporte.set({ menu: false })} style={{ position: 'fixed', inset: 0, zIndex: 900 }}/>
          <div className="ax-fade-in" data-s="menu-ayuda" style={{
            position: 'absolute', right: 0, top: 36, zIndex: 901, width: 300, padding: 6,
            background: 'var(--ax-bg-2)', border: '1px solid var(--ax-border-strong)', borderRadius: 10, boxShadow: 'var(--ax-shadow-modal)',
          }}>
            <div style={{ padding: '6px 12px 4px' }}><AxEyebrow>Ayuda</AxEyebrow></div>
            <AyudaItem dataS="menu-reportar" onClick={() => AxReporte.abrir()} sub="Algo falla o no hace lo que esperabas">Reportar un problema…</AyudaItem>
            <AyudaItem dataS="menu-cuentanos" onClick={() => { AxReporte.set({ menu: false }); toast('En la app real, «Cuéntanos» abre en tu navegador la página para dejar una idea o algo que te falta.'); }} sub="Una idea o algo que te falta">Cuéntanos</AyudaItem>
            {rc.qUbicacion === 'A' ? <AyudaItem dataS="menu-recomienda" onClick={() => AxRecomienda.abrir()} sub="Por WhatsApp, con la liga de descarga">Recomienda Piixi a un colega</AyudaItem> : null}
            <div style={{ height: 1, background: 'var(--ax-border)', margin: '6px 4px' }}/>
            <AyudaItem onClick={() => { AxReporte.set({ menu: false }); toast('Novedades de esta versión (ya existe en la app).'); }}>Novedades de esta versión</AyudaItem>
            <AyudaItem onClick={() => { AxReporte.set({ menu: false }); toast('Buscar actualizaciones… (ya existe en la app).'); }}>Buscar actualizaciones…</AyudaItem>
            <div style={{ padding: '6px 12px 4px', fontSize: 11, color: 'var(--ax-fg-faint)', lineHeight: 1.45 }}>En la app de escritorio, este mismo menú también está en la barra del sistema › Ayuda.</div>
          </div>
        </>
      ) : null}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// REPORTAR UN PROBLEMA — formulario (sirve al diálogo y a la pantalla)
// ─────────────────────────────────────────────────────────────
function RptCapturaVista() {
  return (
    <div style={{ width: 200, height: 118, borderRadius: 6, border: '1px solid var(--ax-border-strong)', background: 'var(--ax-bg)', padding: 6, display: 'flex', gap: 5 }}>
      <div style={{ width: 34, background: 'var(--ax-bg-1)', borderRadius: 3 }}/>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 4 }}>
        <div style={{ height: 10, background: 'var(--ax-bg-2)', borderRadius: 3 }}/>
        {[0, 1, 2, 3, 4].map((i) => <div key={i} style={{ height: 9, width: (90 - i * 9) + '%', background: 'var(--ax-bg-3)', borderRadius: 3 }}/>)}
        <div style={{ marginTop: 'auto', height: 14, width: '60%', background: 'var(--ax-danger-soft)', border: '1px solid var(--ax-danger)', borderRadius: 3 }}/>
      </div>
    </div>
  );
}

function RptQueSeManda({ r }) {
  const diag = AxReporte.diag();
  const so = window.AxNube && AxNube.get().soP === 'win' ? 'Windows 11' : 'macOS 15.1';
  const ver = typeof PIIXI_VERSION !== 'undefined' ? PIIXI_VERSION : '0.3.2';
  const lineas = [
    ['Lo que escribiste', rptTachar(r.descripcion.trim()) || '(vacío)'],
    ...(diag ? [
      ['Versión de Piixi', ver],
      ['Sistema', so],
      ['Pantalla', rptPantalla(r.desde)],
      ['Último error', r.error ? r.error.codigo + ' · ' + r.error.mensaje : 'ninguno en esta sesión'],
    ] : []),
    ...(r.captura && r.qCaptura === 'B' ? [['Captura de pantalla', '1 imagen (la de arriba)']] : []),
    ['Tu cuenta', 'el correo con el que entraste, para poder responderte'],
  ];
  return (
    <div data-s="que-se-manda" style={{ border: '1px solid var(--ax-border)', borderRadius: 8, background: 'var(--ax-bg-1)' }}>
      <div style={{ padding: '8px 12px', borderBottom: '1px solid var(--ax-border)' }}><AxEyebrow>Exactamente esto se manda</AxEyebrow></div>
      <div style={{ padding: '8px 12px', display: 'flex', flexDirection: 'column', gap: 6 }}>
        {lineas.map(([k, v]) => (
          <div key={k} style={{ display: 'grid', gridTemplateColumns: '140px 1fr', gap: 10, fontSize: 12 }}>
            <span style={{ color: 'var(--ax-fg-muted)' }}>{k}</span>
            <span className="ax-mono" style={{ color: 'var(--ax-fg-strong)', whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' }}>{v}</span>
          </div>
        ))}
      </div>
      <div style={{ padding: '8px 12px', borderTop: '1px solid var(--ax-border)', fontSize: 12, color: 'var(--ax-fg-muted)', lineHeight: 1.5 }}>
        <b style={{ color: 'var(--ax-fg-strong)', fontWeight: 600 }}>No se manda:</b> pólizas, clientes, documentos, nombres de archivo ni nada de tu cartera.
        {r.error && r.error.archivo ? ' El nombre del archivo que falló («' + r.error.archivo + '») se queda aquí.' : ''}
      </div>
    </div>
  );
}

function RptFormulario({ enPantalla }) {
  const r = useReporte();
  const { navigate } = useHashRoute();
  const diag = AxReporte.diag();
  const n = r.descripcion.length;
  const vacio = !r.descripcion.trim();
  if (r.resultado) {
    const f = r.resultado.folio;
    return (
      <div data-s={r.resultado.cola ? 'reporte-en-cola' : 'reporte-enviado'} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {r.resultado.cola ? (
          <NbAviso tono="warm" icono="alert" titulo={'Sin internet: tu reporte ' + f + ' quedó en cola'}>
            Se guardó en esta computadora y se manda solo en cuanto vuelva internet. No tienes que hacer nada; lo puedes seguir en Mis reportes.
          </NbAviso>
        ) : (
          <NbAviso tono="ok" icono="check" titulo={'Tu reporte ' + f + ' quedó registrado'}>
            Lo revisamos en orden de llegada. Si necesitamos algo más, te escribimos al correo de tu cuenta. Lo puedes seguir en Ajustes › Ayuda y soporte › Mis reportes.
          </NbAviso>
        )}
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <AxButton variant="secondary" icon="copy" onClick={() => { if (window.pregCopiar) pregCopiar(f); window.__nbToast && window.__nbToast({ kind: 'info', message: 'Folio copiado: ' + f }); }}>Copiar folio</AxButton>
          <AxButton variant="secondary" onClick={() => { AxReporte.cerrar(); navigate('/ajustes/reportes'); }}>Ver mis reportes</AxButton>
          {!enPantalla ? <AxButton variant="primary" onClick={() => AxReporte.cerrar()}>Cerrar</AxButton> : <AxButton variant="primary" onClick={() => { AxReporte.cerrar(); navigate('/ajustes/reportes'); }}>Listo</AxButton>}
        </div>
      </div>
    );
  }
  return (
    <div data-s="form-reporte" style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      {r.error ? (
        <NbAviso tono="bad" icono="alert" dataNb="error-llenado" titulo="El error de la pantalla ya va incluido">
          <span className="ax-mono" style={{ fontSize: 12 }}>{r.error.codigo}</span> · {r.error.mensaje} · {r.error.pantalla}, hace un momento.
        </NbAviso>
      ) : null}
      <AxField label="¿Qué pasó?" error={n > 2000 ? 'Son ' + n + ' caracteres; el máximo es 2,000.' : null}
        helper={'No escribas nombres de clientes ni números de póliza. Si se cuela un RFC o una CURP, Piixi lo tacha antes de mandar. · ' + n.toLocaleString('es-MX') + ' / 2,000'}>
        <AxTextarea rows={5} value={r.descripcion} maxLength={2400} onChange={(e) => AxReporte.set({ descripcion: e.target.value })}
          placeholder="Qué estabas haciendo, qué esperabas que pasara y qué pasó."/>
      </AxField>
      {r.qCaptura === 'B' ? (
        r.captura ? (
          <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
            <RptCapturaVista/>
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 8 }}>
              <NbAviso tono="warm" icono="alert">Revisa que no se vean datos de tus clientes: la captura sí puede traerlos. Si se ven, quítala.</NbAviso>
              <div><AxButton size="sm" variant="secondary" icon="x" onClick={() => AxReporte.set({ captura: false })}>Quitar la captura</AxButton></div>
            </div>
          </div>
        ) : <div><AxButton size="sm" variant="secondary" icon="plus" onClick={() => AxReporte.set({ captura: true })}>Agregar captura de pantalla</AxButton></div>
      ) : (
        <NbNota>Sin capturas de pantalla: podrían traer datos de tus clientes, y esos nunca salen de tu computadora.</NbNota>
      )}
      <label style={{ display: 'flex', gap: 8, alignItems: 'flex-start', fontSize: 13, color: 'var(--ax-fg)' }}>
        <input type="checkbox" data-s="incluir-diag" checked={diag} onChange={(e) => AxReporte.set({ incluirDiag: e.target.checked })} style={{ marginTop: 3 }}/>
        <span>Incluir información técnica <span style={{ color: 'var(--ax-fg-muted)' }}>(versión, sistema, pantalla y último error; sin datos de clientes)</span></span>
      </label>
      <RptQueSeManda r={r}/>
      {rptUsoApagado() ? <NbNota>Tienes los datos de uso apagados. Mandar este reporte cuenta como permiso sólo para este reporte.</NbNota> : null}
      {!r.internet ? <NbNota>Esta computadora está sin internet: el reporte se guarda aquí y sale solo cuando vuelva.</NbNota> : null}
      <NbNota>¿Es una idea o algo que te falta, no una falla? Usa «Cuéntanos» en el menú Ayuda.</NbNota>
      <div style={{ display: 'flex', gap: 8, justifyContent: enPantalla ? 'flex-start' : 'flex-end', alignItems: 'center' }}>
        {vacio ? <span style={{ fontSize: 12, color: 'var(--ax-fg-faint)', marginRight: 'auto' }}>Escribe qué pasó para poder enviarlo.</span> : null}
        {!enPantalla ? <AxButton variant="secondary" onClick={() => AxReporte.cerrar()}>Cancelar</AxButton> : null}
        <AxButton variant="primary" icon="arrow-right" loading={r.enviando} disabled={vacio || n > 2000} onClick={() => AxReporte.enviar()}>{r.enviando ? 'Enviando…' : r.internet ? 'Enviar reporte' : 'Guardar y enviar cuando haya internet'}</AxButton>
      </div>
    </div>
  );
}

function RptDialogo() {
  const r = useReporte();
  return (
    <AxModal open={r.abierto} onClose={() => AxReporte.cerrar()} title="Reportar un problema" width={660}>
      <div style={{ maxHeight: 'calc(100vh - 220px)', overflow: 'auto', paddingRight: 4 }}><RptFormulario/></div>
    </AxModal>
  );
}

// Aviso de error en pantalla (simulado) con «Reportar este problema»
function RptErrorEnPantalla() {
  const r = useReporte();
  const e = r.errorEnPantalla;
  if (!e) return null;
  return (
    <div className="ax-fade-in" data-s="error-en-pantalla" style={{ position: 'fixed', top: 'calc(var(--ax-topbar-h) + 128px)', left: '50%', transform: 'translateX(-30%)', zIndex: 850, width: 560, maxWidth: 'calc(100vw - 60px)' }}>
      <div style={{ background: 'var(--ax-bg-2)', border: '1px solid var(--ax-danger)', borderLeft: '3px solid var(--ax-danger)', borderRadius: 8, padding: '12px 14px', boxShadow: 'var(--ax-shadow-toast)', display: 'flex', gap: 12 }}>
        <span style={{ color: 'var(--ax-danger)', marginTop: 1 }}><AxIcon name="alert" size={16}/></span>
        <div style={{ flex: 1, fontSize: 13, color: 'var(--ax-fg)', lineHeight: 1.5 }}>
          <div style={{ color: 'var(--ax-fg-strong)', fontWeight: 600 }}>No se pudo leer «{e.archivo}»</div>
          <div>La regla de la aseguradora no reconoce este formato. <span className="ax-mono" style={{ fontSize: 11.5, color: 'var(--ax-fg-muted)' }}>Código {e.codigo}</span></div>
          <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
            <AxButton size="sm" variant="primary" onClick={() => AxReporte.abrir({ error: e })}>Reportar este problema</AxButton>
            <AxButton size="sm" variant="tertiary" onClick={() => AxReporte.set({ errorEnPantalla: null })}>Cerrar</AxButton>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// MIS REPORTES · /ajustes/reportes
// ─────────────────────────────────────────────────────────────
function ReportesScreen() {
  const r = useReporte();
  const { path, navigate } = useHashRoute();
  const nuevo = /nuevo=1/.test(path);
  useEffect(() => {
    if (nuevo && r.qContenedor === 'A' && !r.abierto && !r.resultado) AxReporte.set({ abierto: true });
  }, [nuevo]);
  const enPantalla = nuevo && r.qContenedor === 'B';
  return (
    <div style={{ flex: 1, overflow: 'auto' }} className="ax-fade-in">
      <AxPageHeader eyebrow="Ajustes › Ayuda y soporte" title={enPantalla ? 'Reportar un problema' : 'Mis reportes'}
        subtitle={enPantalla ? 'Cuéntanos qué falla. Antes de enviar ves exactamente qué se manda.' : 'Los problemas que reportaste desde esta computadora, con su folio y en qué van.'}
        actions={enPantalla ? <AxButton variant="tertiary" icon="arrow-left" onClick={() => navigate('/ajustes/reportes')}>Mis reportes</AxButton> : <AxButton variant="primary" icon="plus" onClick={() => AxReporte.abrir()}>Reportar un problema</AxButton>}/>
      <div style={{ padding: '24px 32px 48px', maxWidth: 900, display: 'flex', flexDirection: 'column', gap: 18 }}>
        {enPantalla ? (
          <div className="ax-card" style={{ padding: 18 }}><RptFormulario enPantalla/></div>
        ) : null}
        <div className="ax-card" data-s="mis-reportes">
          {r.reportes.length === 0 ? (
            <AxEmpty icon="inbox" title="Todavía no has reportado nada" body="Cuando algo falle, usa Ayuda › Reportar un problema."/>
          ) : r.reportes.map((x, i) => {
            const e = RPT_ESTADOS[x.estado];
            return (
              <div key={x.folio} data-s="reporte" data-estado={x.estado} style={{ padding: '14px 18px', borderTop: i ? '1px solid var(--ax-border)' : 'none', display: 'flex', gap: 14, alignItems: 'flex-start', flexWrap: 'wrap' }}>
                <div style={{ flex: '1 1 340px', minWidth: 0 }}>
                  <div style={{ display: 'flex', gap: 10, alignItems: 'baseline', flexWrap: 'wrap' }}>
                    <span className="ax-mono" style={{ fontSize: 12.5, color: 'var(--ax-fg-strong)' }}>{x.folio}</span>
                    <span style={{ fontSize: 12, color: 'var(--ax-fg-muted)' }}>{x.fecha}</span>
                  </div>
                  <div style={{ fontSize: 13, color: 'var(--ax-fg)', marginTop: 4 }}>{x.resumen}</div>
                  <div style={{ fontSize: 12, color: 'var(--ax-fg-muted)', marginTop: 4 }}>{e.texto}</div>
                </div>
                <AxPill tone={e.tono} dot={x.estado === 'resuelto'}>{e.l}</AxPill>
              </div>
            );
          })}
        </div>
        <NbNota>En qué va cada uno: en cola (sin internet, sale solo) · enviado · recibido · en revisión · resuelto.</NbNota>
      </div>
    </div>
  );
}

// Ajustes: tarjeta «Ayuda y soporte»
function SoporteTarjeta() {
  const r = useReporte();
  const rc = useRecomienda();
  const { navigate } = useHashRoute();
  const abiertos = r.reportes.filter((x) => x.estado !== 'resuelto').length;
  const filas = [
    { l: 'Reportar un problema', v: 'Lo que escribes y la información técnica; nada de tu cartera', on: () => AxReporte.abrir(), s: 'ajustes-reportar' },
    { l: 'Mis reportes', v: r.reportes.length + (r.reportes.length === 1 ? ' reporte' : ' reportes') + (abiertos ? ' · ' + abiertos + ' sin resolver' : ''), on: () => navigate('/ajustes/reportes'), s: 'ajustes-mis-reportes',
      pill: r.reportes.some((x) => x.estado === 'en_cola') ? { tone: 'warm', label: 'en cola' } : null },
    { l: 'Recomienda Piixi', v: 'A un colega, por WhatsApp' + (rc.usos ? ' · lo usaste ' + rc.usos + (rc.usos === 1 ? ' vez' : ' veces') : ''), on: () => AxRecomienda.abrir(), s: 'ajustes-recomienda' },
  ];
  return (
    <div className="ax-card" data-s="tarjeta-soporte">
      <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--ax-border)', display: 'flex', alignItems: 'center', gap: 10 }}>
        <AxIcon name="help" size={15} style={{ color: 'var(--ax-fg-muted)' }}/>
        <h3 style={{ margin: 0, fontSize: 14, fontWeight: 500, color: 'var(--ax-fg-strong)' }}>Ayuda y soporte</h3>
      </div>
      {filas.map((it, i) => (
        <button key={it.l} data-s={it.s} onClick={it.on} style={{
          appearance: 'none', background: 'transparent', border: 0, width: '100%', textAlign: 'left', padding: '12px 18px',
          borderTop: i > 0 ? '1px solid var(--ax-border)' : 'none', display: 'grid', gridTemplateColumns: '180px 1fr auto', gap: 14, alignItems: 'center',
          color: 'inherit', cursor: 'default', fontSize: 13,
        }}
          onMouseEnter={(e) => e.currentTarget.style.background = 'var(--ax-bg-3)'}
          onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
          <span style={{ color: 'var(--ax-fg-muted)' }}>{it.l}</span>
          <span style={{ color: 'var(--ax-fg-strong)' }}>{it.v}</span>
          <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            {it.pill ? <AxPill tone={it.pill.tone}>{it.pill.label}</AxPill> : null}
            <AxIcon name="chevron-right" size={12} style={{ color: 'var(--ax-fg-faint)' }}/>
          </span>
        </button>
      ))}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// RECOMIENDA PIIXI
// ─────────────────────────────────────────────────────────────
const RCM_CHATS = ['Agentes Zona Norte (grupo)', 'Carlos Ejemplo', 'Mariana Ejemplo'];

function RecomiendaDialogo() {
  const rc = useRecomienda();
  const msg = AxRecomienda.mensaje();
  const [copiado, setCopiado] = useState(false);
  return (
    <>
      <AxModal open={rc.abierto && !rc.whatsapp} onClose={() => AxRecomienda.set({ abierto: false })} title="Recomienda Piixi a un colega" width={540}
        footer={<>
          <AxButton variant="secondary" icon="copy" onClick={() => { if (window.pregCopiar) pregCopiar(msg); setCopiado(true); setTimeout(() => setCopiado(false), 2500); }}>{copiado ? 'Copiado' : 'Copiar mensaje'}</AxButton>
          <AxButton variant="primary" icon="arrow-right" onClick={() => AxRecomienda.set({ whatsapp: true, chat: null })}>Abrir WhatsApp</AxButton>
        </>}>
        <div data-s="recomienda" style={{ display: 'flex', flexDirection: 'column', gap: 12, fontSize: 13, color: 'var(--ax-fg)', lineHeight: 1.55 }}>
          <div>Piixi básico es gratuito siempre y sin candados. Si te sirve, pásalo a un colega: se abre WhatsApp con este mensaje y tú eliges a quién mandarlo.</div>
          <div data-s="mensaje" style={{ whiteSpace: 'pre-wrap', background: 'var(--ax-bg-1)', border: '1px solid var(--ax-border)', borderRadius: 8, padding: '12px 14px', color: 'var(--ax-fg-strong)' }}>{msg}</div>
          <NbNota>Lo puedes cambiar en WhatsApp antes de mandarlo. Durante la beta, la liga lleva a una lista de espera: tu colega se anota y le avisamos cuando tenga lugar.</NbNota>
          <NbNota>Piixi sólo cuenta que usaste este botón: no sabe a quién se lo mandas ni lo que dice el mensaje.</NbNota>
        </div>
      </AxModal>
      <NbSistema open={rc.abierto && rc.whatsapp} titulo="WhatsApp · elige a quién mandarlo" ancho={460}
        botones={<><NbSisBoton onClick={() => AxRecomienda.set({ whatsapp: false })}>Cancelar</NbSisBoton><NbSisBoton primario disabled={!rc.chat} onClick={() => AxRecomienda.mandado()}>Enviar</NbSisBoton></>}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <div style={{ background: '#fff', border: '1px solid rgba(0,0,0,.12)', borderRadius: 6 }}>
            {RCM_CHATS.map((c) => (
              <button key={c} type="button" data-s="chat" onClick={() => AxRecomienda.set({ chat: c })} style={{
                appearance: 'none', display: 'block', width: '100%', textAlign: 'left', border: 0, padding: '8px 10px', font: 'inherit', cursor: 'default',
                background: rc.chat === c ? '#0A7AFF' : 'transparent', color: rc.chat === c ? '#fff' : '#1d1d1f',
              }}>{c}</button>
            ))}
          </div>
          <div style={{ background: '#fff', border: '1px solid rgba(0,0,0,.12)', borderRadius: 6, padding: '8px 10px', whiteSpace: 'pre-wrap', fontSize: 12.5, color: '#1d1d1f' }}>{msg}</div>
          <div style={{ fontSize: 11.5, color: '#6e6e73' }}>Simulado: en la app real se abre WhatsApp (de escritorio o web) con el mensaje ya escrito.</div>
        </div>
      </NbSistema>
    </>
  );
}

// Inicio: tarjeta pequeña (sólo con la respuesta B de «dónde vive el botón»)
function RecomiendaInicio() {
  const rc = useRecomienda();
  if (rc.qUbicacion !== 'B' || rc.ocultaInicio) return null;
  return (
    <div style={{ padding: '16px 32px 0' }}>
      <div data-s="recomienda-inicio" style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '12px 16px', borderRadius: 10, background: 'var(--ax-accent-soft)', border: '1px solid var(--ax-accent-line)', flexWrap: 'wrap' }}>
        <AxIcon name="user" size={16} style={{ color: 'var(--ax-accent)' }}/>
        <div style={{ flex: '1 1 320px', fontSize: 13, color: 'var(--ax-fg)' }}>
          <b style={{ color: 'var(--ax-fg-strong)', fontWeight: 600 }}>¿Piixi te ahorra tiempo?</b> Pásalo a un colega: es gratuito.
        </div>
        <AxButton size="sm" variant="primary" onClick={() => AxRecomienda.abrir()}>Recomendar por WhatsApp</AxButton>
        <AxButton size="sm" variant="tertiary" icon="x" onClick={() => AxRecomienda.set({ ocultaInicio: true })}>Ahora no</AxButton>
      </div>
    </div>
  );
}

// Lo que ve el colega al abrir la liga: página de lista de espera (fuera de la app)
function EsperaMarco({ children }) {
  return (
    <div style={{ minHeight: '100%', background: 'var(--ax-bg)', display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '48px 20px', boxSizing: 'border-box' }}>
      <div style={{ width: '100%', maxWidth: 520, display: 'flex', flexDirection: 'column', gap: 20 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          {window.AxLogo ? <AxLogo size={26}/> : <b>piixi.</b>}
          <span className="ax-mono" style={{ fontSize: 10.5, color: 'var(--ax-fg-faint)', letterSpacing: '.12em' }}>PÁGINA WEB · LO QUE VE TU COLEGA</span>
        </div>
        {children}
      </div>
    </div>
  );
}

function EsperaScreen() {
  const rc = useRecomienda();
  const [correo, setCorreo] = useState('');
  const [cedula, setCedula] = useState('');
  const [aviso, setAviso] = useState(false);
  const [intento, setIntento] = useState(false);
  const errCorreo = intento && !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(correo) ? 'Escribe un correo válido.' : null;
  const errCedula = intento && !/^[A-Za-z]?-?\d{5,8}$/.test(cedula.trim()) ? 'Escribe el número de tu cédula, como aparece en ella (p. ej. A-0123456).' : null;
  const anotar = () => { setIntento(true); if (/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(correo) && /^[A-Za-z]?-?\d{5,8}$/.test(cedula.trim()) && aviso) AxRecomienda.anotar(correo, cedula.trim()); };
  if (rc.espera.paso === 'anotado') {
    return (
      <EsperaMarco>
        <div className="ax-card" data-s="espera-anotado" style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 12 }}>
          <div style={{ fontSize: 22, fontWeight: 600, color: 'var(--ax-fg-strong)' }}>Ya estás en la lista</div>
          <div style={{ fontSize: 14, color: 'var(--ax-fg)', lineHeight: 1.6 }}>
            Te escribimos a <b style={{ color: 'var(--ax-fg-strong)' }}>{rc.espera.correo}</b> cuando tengas lugar. No tienes que hacer nada más.
          </div>
          <NbFila etiqueta="Cédula">{rc.espera.cedula}</NbFila>
          <NbFila etiqueta="Estado">{rc.aprobado ? 'Aprobado: revisa tu correo' : 'En lista de espera'}</NbFila>
          <NbNota>Piixi básico es gratuito siempre. La beta tiene lugares limitados para acompañar bien a cada agente.</NbNota>
        </div>
      </EsperaMarco>
    );
  }
  return (
    <EsperaMarco>
      <div>
        <div style={{ fontSize: 28, fontWeight: 600, color: 'var(--ax-fg-strong)', letterSpacing: '-0.01em' }}>Piixi está en beta</div>
        <div style={{ fontSize: 15, color: 'var(--ax-fg)', lineHeight: 1.6, marginTop: 8 }}>
          Un colega te pasó esta liga. Piixi carga tu cartera desde los portales de las aseguradoras y te ayuda con la cobranza y las renovaciones. Es gratuito.
        </div>
        <div style={{ fontSize: 14, color: 'var(--ax-fg-muted)', lineHeight: 1.6, marginTop: 8 }}>
          Durante la beta, cada lugar lo aprueba el equipo de Piixi. Anótate y te avisamos por correo.
        </div>
      </div>
      <div className="ax-card" data-s="espera-form" style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 14 }}>
        <AxField label="Tu correo" error={errCorreo}><AxInput type="email" value={correo} onChange={(e) => setCorreo(e.target.value)} placeholder="tu.correo@ejemplo.com"/></AxField>
        <AxField label="Tu cédula de agente" error={errCedula} helper="Durante la beta, Piixi es para agentes de seguros con cédula."><AxInput value={cedula} onChange={(e) => setCedula(e.target.value)} placeholder="A-0123456"/></AxField>
        <label style={{ display: 'flex', gap: 8, alignItems: 'flex-start', fontSize: 13, color: 'var(--ax-fg)' }}>
          <input type="checkbox" checked={aviso} onChange={(e) => setAviso(e.target.checked)} style={{ marginTop: 3 }}/>
          <span>Leí el <u>aviso de privacidad</u>: mi correo y mi cédula sólo se usan para darme lugar en la beta.</span>
        </label>
        {intento && !aviso ? <div style={{ fontSize: 12, color: 'var(--ax-danger)' }}>Marca que leíste el aviso de privacidad.</div> : null}
        <div><AxButton variant="primary" onClick={anotar}>Anotarme en la lista</AxButton></div>
      </div>
    </EsperaMarco>
  );
}

// El aviso cuando lo aprueban: el correo que le llega
function EsperaAvisoScreen() {
  const rc = useRecomienda();
  const correo = rc.espera.correo || 'colega.ejemplo@gmail.com';
  return (
    <div style={{ minHeight: '100%', background: 'var(--ax-bg)', padding: '40px 20px', boxSizing: 'border-box', display: 'flex', justifyContent: 'center' }}>
      <div style={{ width: '100%', maxWidth: 620, display: 'flex', flexDirection: 'column', gap: 12 }}>
        <span className="ax-mono" style={{ fontSize: 10.5, color: 'var(--ax-fg-faint)', letterSpacing: '.12em' }}>SU CORREO · EL AVISO CUANDO LO APRUEBAN</span>
        {!rc.aprobado ? (
          <NbAviso tono="info" icono="info" titulo="Todavía no lo aprueban">En «Simular», toca «El equipo de Piixi aprueba al colega» para ver el correo que le llega.</NbAviso>
        ) : (
          <div className="ax-card" data-s="correo-aprobado" style={{ overflow: 'hidden' }}>
            <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--ax-border)', display: 'flex', flexDirection: 'column', gap: 3, fontSize: 12.5, color: 'var(--ax-fg-muted)' }}>
              <span><b style={{ color: 'var(--ax-fg-strong)' }}>De:</b> Piixi</span>
              <span><b style={{ color: 'var(--ax-fg-strong)' }}>Para:</b> {correo}</span>
              <span style={{ fontSize: 15, color: 'var(--ax-fg-strong)', marginTop: 4 }}>Ya tienes lugar en Piixi</span>
            </div>
            <div style={{ padding: '18px', display: 'flex', flexDirection: 'column', gap: 12, fontSize: 14, color: 'var(--ax-fg)', lineHeight: 1.6 }}>
              <div>Hola: ya puedes instalar Piixi.</div>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                <AxButton variant="primary" onClick={() => window.__nbToast && window.__nbToast({ kind: 'info', message: 'En el correo real, baja el instalador para Mac.' })}>Descargar para Mac</AxButton>
                <AxButton variant="primary" onClick={() => window.__nbToast && window.__nbToast({ kind: 'info', message: 'En el correo real, baja el instalador para Windows.' })}>Descargar para Windows</AxButton>
              </div>
              <div>Al abrirlo, crea tu cuenta con este mismo correo: así Piixi sabe que ya tienes lugar.</div>
              <div style={{ fontSize: 12.5, color: 'var(--ax-fg-muted)' }}>Piixi básico es gratuito siempre. Si tienes dudas, contesta este correo.</div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// Capa global: diálogos y avisos que se abren encima de cualquier pantalla
function SoporteCapa() {
  const { pushToast } = useAxStore();
  window.__nbToast = pushToast;
  return (<><RptDialogo/><RptErrorEnPantalla/><RecomiendaDialogo/></>);
}

// ─────────────────────────────────────────────────────────────
// PANEL «SIMULAR» · Reportar un problema (#812) + Recomienda Piixi
// ─────────────────────────────────────────────────────────────
function SoporteTweaks({ navigate }) {
  const r = useReporte();
  const rc = useRecomienda();
  const [copiado, setCopiado] = useState(false);
  const cerrarTodo = () => { AxReporte.set({ abierto: false, resultado: null, menu: false }); AxRecomienda.set({ abierto: false, whatsapp: false }); };
  const recorridos = [
    { t: '1 · Reportar un problema desde el menú Ayuda', f: () => { cerrarTodo(); AxReporte.set({ internet: true }); navigate('/polizas'); setTimeout(() => AxReporte.set({ menu: true }), 50); }, nota: 'Se abre el menú del botón «?» arriba a la derecha.' },
    { t: '2 · Un error en Importar → «Reportar este problema» (ya llenado)', f: () => { cerrarTodo(); AxReporte.set({ internet: true }); navigate('/importar'); AxReporte.simularError(); } },
    { t: '3 · Sin internet: el reporte queda en cola y sale solo', f: () => { cerrarTodo(); AxReporte.set({ internet: false }); navigate('/inicio'); AxReporte.abrir(); }, nota: 'Después toca «Vuelve internet» abajo y mira Mis reportes.' },
    { t: '4 · Mis reportes: folio y en qué va cada uno', f: () => { cerrarTodo(); navigate('/ajustes/reportes'); } },
  ];
  const recRecorridos = [
    { t: '1 · Recomendar Piixi por WhatsApp', f: () => { cerrarTodo(); if (rc.qUbicacion === 'B') { AxRecomienda.set({ ocultaInicio: false }); navigate('/inicio'); } else { navigate('/inicio'); setTimeout(() => AxReporte.set({ menu: true }), 50); } }, nota: rc.qUbicacion === 'B' ? 'Con B, la tarjeta está arriba en Inicio.' : 'Con A, está en el menú del botón «?».' },
    { t: '2 · Lo que ve tu colega al abrir la liga (lista de espera)', f: () => { cerrarTodo(); AxRecomienda.reiniciarEspera(); navigate('/espera'); } },
    { t: '3 · El equipo de Piixi lo aprueba: el correo que le llega', f: () => { cerrarTodo(); if (AxRecomienda.get().espera.paso !== 'anotado') AxRecomienda.anotar('colega.ejemplo@gmail.com', 'A-0123456'); AxRecomienda.set({ aprobado: true }); navigate('/espera/aviso'); } },
  ];
  const preguntas = [
    { texto: '«Reportar un problema», ¿se abre encima de la pantalla donde estás o en una pantalla aparte?', valor: r.qContenedor,
      a: 'Encima, como diálogo: no pierdes lo que estabas haciendo y la pantalla va en la información técnica', b: 'En una pantalla aparte, en Ajustes › Ayuda y soporte',
      elegir: (v) => AxReporte.set({ qContenedor: v }), donde: 'Ayuda › Reportar un problema', ir: () => { cerrarTodo(); navigate('/polizas'); setTimeout(() => AxReporte.set({ menu: true }), 50); } },
    { texto: '¿El reporte puede llevar una captura de pantalla?', valor: r.qCaptura,
      a: 'No: una captura puede traer datos de clientes, y esos nunca salen de la computadora', b: 'Sí, opcional: se ve antes de enviar, con aviso y botón para quitarla',
      elegir: (v) => AxReporte.set({ qCaptura: v, captura: false }), donde: 'el formulario del reporte', ir: () => { cerrarTodo(); navigate('/inicio'); AxReporte.abrir(); } },
    { texto: 'La información técnica (versión, sistema, pantalla, último error), ¿va marcada?', valor: r.qDiag,
      a: 'Sí, marcada: el agente la ve y la puede quitar', b: 'No: va desmarcada y el agente la marca si quiere',
      elegir: (v) => AxReporte.set({ qDiag: v, incluirDiag: null }), donde: 'el formulario, en «Exactamente esto se manda»', ir: () => { cerrarTodo(); navigate('/importar'); AxReporte.simularError(); } },
    { texto: '«Recomienda Piixi a un colega», ¿dónde vive el botón?', valor: rc.qUbicacion,
      a: 'En el menú Ayuda (y en Ajustes): discreto, no estorba el trabajo del día', b: 'En una tarjeta pequeña en Inicio, que se puede cerrar: más a la vista',
      elegir: (v) => AxRecomienda.set({ qUbicacion: v, ocultaInicio: false }), donde: 'el menú «?» o Inicio', ir: () => { cerrarTodo(); navigate('/inicio'); if (AxRecomienda.get().qUbicacion === 'A') setTimeout(() => AxReporte.set({ menu: true }), 50); } },
    { texto: 'El mensaje de WhatsApp, ¿avisa que en la beta hay lista de espera?', valor: rc.qBeta,
      a: 'Sí: «está en beta: te anotas en la liga y te avisan por correo»', b: 'No: sólo «descárgalo aquí»; la página explica la lista',
      elegir: (v) => AxRecomienda.set({ qBeta: v }), donde: 'el mensaje de «Recomienda Piixi»', ir: () => { cerrarTodo(); navigate('/inicio'); AxRecomienda.abrir(); } },
  ];
  const resumen = 'Reportar un problema (#812) y Recomienda Piixi:\n' + preguntas.map((q, i) => (i + 1) + '. ' + q.texto + '\n   → ' + q.valor + ': ' + (q.valor === 'B' ? q.b : q.a)).join('\n');
  const copiar = () => { if (window.pregCopiar) pregCopiar(resumen); setCopiado(true); setTimeout(() => setCopiado(false), 4000); };
  return (
    <>
      <TweakSection label="Reportar un problema (#812) · para validar"/>
      <div style={{ fontSize: 11, color: '#444', lineHeight: 1.45 }}>
        Desde el menú Ayuda (botón «?» de arriba), desde un error en pantalla o desde Ajustes › Ayuda y soporte. Antes de enviar se ve exactamente qué se manda; nada de la cartera.
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4, marginTop: 6 }}>
        {recorridos.map((x, i) => (
          <div key={i} style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            <NbTwkBtn onClick={x.f}>→ {x.t}</NbTwkBtn>
            {x.nota ? <div style={{ ...nbNotaTwk, paddingLeft: 8 }}>{x.nota}</div> : null}
          </div>
        ))}
      </div>
      <TweakRadio label="Internet de esta computadora" value={r.internet ? 'si' : 'no'} options={[{ value: 'si', label: 'Con internet' }, { value: 'no', label: 'Sin internet' }]}
        onChange={(v) => { if (v === 'si') AxReporte.volvioInternet(); else AxReporte.set({ internet: false }); }}/>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        <NbTwkBtn onClick={() => AxReporte.volvioInternet()}>→ Vuelve internet (lo que estaba en cola sale solo)</NbTwkBtn>
        <NbTwkBtn onClick={() => AxReporte.avanzarRevision()}>→ El equipo de Piixi lo pone «en revisión»</NbTwkBtn>
        <NbTwkBtn onClick={() => AxReporte.simularError()}>→ Mostrar un error en esta pantalla</NbTwkBtn>
      </div>

      <TweakSection label="Recomienda Piixi a un colega · para validar"/>
      <div style={{ fontSize: 11, color: '#444', lineHeight: 1.45 }}>
        Abre WhatsApp con el mensaje y la liga; sólo se cuenta que se usó ({rc.usos} {rc.usos === 1 ? 'vez' : 'veces'} en esta sesión). En la beta, la liga lleva a la lista de espera.
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4, marginTop: 6 }}>
        {recRecorridos.map((x, i) => (
          <div key={i} style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            <NbTwkBtn onClick={x.f}>→ {x.t}</NbTwkBtn>
            {x.nota ? <div style={{ ...nbNotaTwk, paddingLeft: 8 }}>{x.nota}</div> : null}
          </div>
        ))}
        <NbTwkBtn onClick={() => { AxRecomienda.set({ aprobado: true }); navigate('/espera/aviso'); }}>→ El equipo de Piixi aprueba al colega</NbTwkBtn>
      </div>

      <TweakSection label="Preguntas para ti · reportar y recomendar"/>
      <div>
        {preguntas.map((q, i) => (
          <div key={i} data-s-pregunta={i + 1} style={{ display: 'flex', flexDirection: 'column', gap: 5, padding: '9px 0', borderTop: '1px solid rgba(0,0,0,.08)' }}>
            <div style={{ fontSize: 12, fontWeight: 600, color: '#111', lineHeight: 1.35 }}>{i + 1}. {q.texto}</div>
            <PregBoton letra="A" activo={q.valor === 'A'} onClick={() => q.elegir('A')}><i style={{ fontStyle: 'normal', fontWeight: 600, color: '#0a7a46' }}>Propuesta · </i>{q.a}</PregBoton>
            <PregBoton letra="B" activo={q.valor === 'B'} onClick={() => q.elegir('B')}>{q.b}</PregBoton>
            <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8, alignItems: 'center', fontSize: 10.5, color: '#555' }}>
              <span>Se ve en: {q.donde}</span>
              <button type="button" onClick={q.ir} style={{ flex: '0 0 auto', border: 0, background: 'transparent', color: '#0a7a46', fontWeight: 600, cursor: 'pointer', font: 'inherit', fontSize: 10.5, padding: 0 }}>Llévame ahí →</button>
            </div>
          </div>
        ))}
      </div>
      <button type="button" onClick={copiar} style={{ marginTop: 4, width: '100%', padding: '8px 10px', borderRadius: 7, border: '1px solid #0a7a46', background: copiado ? '#0a7a46' : 'rgba(255,255,255,.8)', color: copiado ? '#fff' : '#0a7a46', font: 'inherit', fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>
        {copiado ? 'Copiado: pégalo en la conversación' : 'Copiar mis respuestas'}
      </button>
    </>
  );
}

Object.assign(window, {
  AxReporte, useReporte, AxRecomienda, useRecomienda,
  AyudaBoton, ReportesScreen, SoporteTarjeta, RecomiendaInicio, EsperaScreen, EsperaAvisoScreen, SoporteCapa, SoporteTweaks,
});
