// src/screen-tema.jsx — Modo claro (#1456, 2026-10-17).
//  · AparienciaTarjeta: Ajustes › Apariencia (selector Oscuro / Claro).
//  · TemaClaroTweaks: bloque del panel «Simular» para recorrer el claro y decidir dos cosas.
// Los dos leen y escriben el mismo estado (window.PiixiTema, en tema.jsx).

function AparienciaTarjeta() {
  const t = window.usePiixiTema();
  const opciones = [['oscuro', 'Oscuro'], ['claro', 'Claro']];
  return (
    <div className="ax-card" id="apariencia">
      <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--ax-border)', display: 'flex', alignItems: 'center', gap: 10 }}>
        <AxIcon name="eye" size={15} style={{ color: 'var(--ax-fg-muted)' }}/>
        <h3 style={{ margin: 0, fontSize: 14, fontWeight: 500, color: 'var(--ax-fg-strong)' }}>Apariencia</h3>
      </div>
      <div style={{ padding: '12px 18px 14px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '180px 1fr', gap: 14, alignItems: 'center', fontSize: 13 }}>
          <span style={{ color: 'var(--ax-fg-muted)' }}>Tema</span>
          <div role="radiogroup" aria-label="Tema" style={{ display: 'inline-flex', justifySelf: 'start', padding: 2, gap: 2, borderRadius: 8, background: 'var(--ax-bg-4)', border: '1px solid var(--ax-border)' }}>
            {opciones.map(([v, l]) => {
              const on = t.tema === v;
              return (
                <button key={v} type="button" role="radio" aria-checked={on} onClick={() => window.PiixiTema.set({ tema: v })}
                  style={{
                    appearance: 'none', border: 0, borderRadius: 6, padding: '6px 18px', font: 'inherit', fontSize: 13, cursor: 'pointer',
                    background: on ? 'var(--ax-bg-2)' : 'transparent', color: on ? 'var(--ax-fg-strong)' : 'var(--ax-fg-muted)',
                    fontWeight: on ? 600 : 400, boxShadow: on ? '0 0 0 1px var(--ax-border-strong)' : 'none',
                  }}>{l}</button>
              );
            })}
          </div>
        </div>
        <div style={{ fontSize: 12, color: 'var(--ax-fg-muted)', lineHeight: 1.45 }}>
          Claro: fondo gris que no deslumbra y letra negra. Se recuerda la próxima vez que abras Piixi.
        </div>
      </div>
    </div>
  );
}

// ── contraste WCAG leído del DOM ───────────────────────────────
function temaRgb(v) {
  v = (v || '').trim();
  let m = v.match(/^#([0-9a-f]{3,8})$/i);
  if (m) { let h = m[1]; if (h.length === 3) h = [...h].map((c) => c + c).join(''); return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16)); }
  m = v.match(/rgba?\(([^)]+)\)/i);
  if (m) return m[1].split(',').slice(0, 3).map((x) => parseFloat(x));
  return null;
}
function temaLum(rgb) {
  const l = (c) => { c /= 255; return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); };
  return 0.2126 * l(rgb[0]) + 0.7152 * l(rgb[1]) + 0.0722 * l(rgb[2]);
}
function temaRatio(a, b) { const [x, y] = [temaLum(a), temaLum(b)].sort((p, q) => q - p); return (x + 0.05) / (y + 0.05); }

function TemaContraste() {
  const cs = getComputedStyle(document.documentElement);
  const tok = (n) => cs.getPropertyValue('--ax-' + n);
  const sup = ['bg', 'bg-1', 'bg-2', 'bg-3', 'bg-4'].map((n) => temaRgb(tok(n))).filter(Boolean);
  const textos = [
    ['fg-strong', 'Texto fuerte'], ['fg', 'Texto'], ['fg-muted', 'Texto secundario'], ['fg-faint', 'Texto tenue'],
    ['accent', 'Al día'], ['warm', 'Pendiente'], ['info', 'Renovación'], ['danger', 'Vencido / peligro'],
  ];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
      {textos.map(([k, nombre]) => {
        const rgb = temaRgb(tok(k));
        if (!rgb || !sup.length) return null;
        const r = Math.min(...sup.map((s) => temaRatio(rgb, s)));
        const ok = r >= 7;
        return (
          <div key={k} style={{ display: 'grid', gridTemplateColumns: '18px 1fr auto 16px', gap: 8, alignItems: 'center', fontSize: 11, color: '#222', padding: '2px 0' }}>
            <span style={{ width: 16, height: 16, borderRadius: 4, background: 'rgb(' + rgb.join(',') + ')', border: '1px solid rgba(0,0,0,.2)' }}/>
            <span>{nombre}</span>
            <span style={{ fontVariantNumeric: 'tabular-nums' }}>{r.toFixed(1)}:1</span>
            <span style={{ color: ok ? '#0a7a46' : '#a11', fontWeight: 700 }}>{ok ? '✔' : '✘'}</span>
          </div>
        );
      })}
      <div style={{ fontSize: 10, color: '#555', lineHeight: 1.4, marginTop: 2 }}>
        Cada texto contra la superficie más desfavorable de las cinco (página, barra de arriba, tarjeta, elevado, campos). Meta: 7:1.
      </div>
    </div>
  );
}

function TemaClaroTweaks({ navigate }) {
  const t = window.usePiixiTema();
  const [copiado, setCopiado] = useState(false);
  const claro = t.tema === 'claro';
  const ir = (ruta) => () => { window.PiixiTema.set({ tema: 'claro' }); navigate(ruta); };

  const preguntas = [
    { texto: '¿Qué tan gris es el fondo?', valor: t.gris === 'medio' ? 'B' : 'A',
      a: 'Gris claro (#E1E1DD)', b: 'Gris medio, un tono más oscuro (#D3D3CE)',
      elegir: (v) => window.PiixiTema.set({ gris: v === 'B' ? 'medio' : 'claro' }),
      donde: 'Inicio, en claro', ir: ir('/inicio') },
    { texto: 'El botón principal (Enviar, Guardar, Aprobar), ¿de qué color va en claro?', valor: t.boton === 'piixi' ? 'B' : 'A',
      a: 'Verde oscuro con letra blanca', b: 'El verde de Piixi (#00FF88) con letra negra',
      elegir: (v) => window.PiixiTema.set({ boton: v === 'B' ? 'piixi' : 'oscuro' }),
      donde: 'Inicio › «Cargar pólizas», en claro', ir: ir('/inicio') },
  ];
  const resumen = 'Modo claro (#1456):\n' + preguntas.map((q, i) => (i + 1) + '. ' + (i === 0 ? 'Fondo' : 'Botón principal') + ' → ' + q.valor + ': ' + (q.valor === 'B' ? q.b : q.a)).join('\n');
  const copiar = () => { pregCopiar(resumen); setCopiado(true); setTimeout(() => setCopiado(false), 4000); };

  const recorrido = [
    ['Inicio', '/inicio'], ['Pólizas (lista)', '/polizas'], ['Póliza con recibo vencido', '/polizas/p0004'],
    ['Su cobranza abierta', '/polizas/p0004?abrir=cobranza&recibo=QUA-760778-03'], ['Pendientes', '/pendientes'],
    ['Clientes', '/clientes'], ['Cumplimiento', '/cumplimiento'], ['Ajustes (zona de peligro al fondo)', '/ajustes'],
    ['Machotes', '/ajustes/machotes'], ['Tu cuenta y equipo', '/cuenta'], ['Sincronización', '/equipo-sincronizacion'],
  ];

  return (
    <>
      <TweakSection label="Modo claro (#1456) · lo que decidiste (17 oct)"/>
      <div style={{ fontSize: 11, color: '#444', lineHeight: 1.4 }}>
        Pedido del despacho piloto: la app se siente muy oscura. Tus dos respuestas ya están en la app y en el issue. La opción descartada sigue aquí para compararla: tócala y la app cambia en ese momento.
      </div>
      <button type="button" onClick={() => window.PiixiTema.set({ tema: claro ? 'oscuro' : 'claro' })}
        style={{ marginTop: 6, width: '100%', padding: '8px 10px', borderRadius: 7, border: '1px solid #111', background: claro ? '#111' : 'rgba(255,255,255,.8)', color: claro ? '#fff' : '#111', font: 'inherit', fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>
        {claro ? 'Volver a oscuro' : 'Ver en claro'}
      </button>
      <div style={{ marginTop: 6 }}>
        {preguntas.map((q, i) => (
          <div key={i} 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>
            {/* 2026-10-17: Miguel eligió A en las dos */}
            <PregBoton letra="A" activo={q.valor === 'A'} onClick={() => q.elegir('A')}><i style={{ fontStyle: 'normal', fontWeight: 600, color: '#0a7a46' }}>Decidido 17 oct · </i>{q.a}</PregBoton>
            <PregBoton letra="B" activo={q.valor === 'B'} onClick={() => q.elegir('B')}><i style={{ fontStyle: 'normal', fontWeight: 600, color: '#999' }}>Descartada · </i>{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>
      <TweakSection label="Recorrido en claro"/>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        {recorrido.map(([l, r]) => <TwkAction key={r} onClick={ir(r)}>→ {l}</TwkAction>)}
      </div>
      {claro ? (<>
        <TweakSection label="Contraste medido"/>
        {/* t se lee arriba: el bloque se vuelve a calcular al cambiar tema o gris */}
        <TemaContraste key={t.tema + t.gris}/>
      </>) : null}
      <button type="button" onClick={copiar} style={{ marginTop: 8, 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, { AparienciaTarjeta, TemaClaroTweaks });
