// LOLA Consola Web — MI PERFIL: datos personales, contraseña y acceso por rostro.
// Estilo LOLA. Exporta window.PerfilView.

// ── Íconos locales ──
const _PI = (p, path) => React.createElement('svg', { width: p.size || 18, height: p.size || 18, viewBox: '0 0 24 24',
  fill: 'none', stroke: 'currentColor', strokeWidth: p.sw || 1.9, strokeLinecap: 'round', strokeLinejoin: 'round' }, path);
const PCam = (p) => _PI(p, [React.createElement('path', { key: 1, d: 'M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z' }), React.createElement('circle', { key: 2, cx: 12, cy: 13, r: 4 })]);
const PPhone = (p) => _PI(p, React.createElement('rect', { x: 7, y: 2, width: 10, height: 20, rx: 2.5 }));
const PLock = (p) => _PI(p, [React.createElement('rect', { key: 1, x: 4, y: 11, width: 16, height: 10, rx: 2 }), React.createElement('path', { key: 2, d: 'M8 11V7a4 4 0 0 1 8 0v4' })]);
const PMail = (p) => _PI(p, [React.createElement('rect', { key: 1, x: 3, y: 5, width: 18, height: 14, rx: 2 }), React.createElement('path', { key: 2, d: 'm3 7 9 6 9-6' })]);
const PUser = (p) => _PI(p, [React.createElement('circle', { key: 1, cx: 12, cy: 8, r: 4 }), React.createElement('path', { key: 2, d: 'M4 21v-1a6 6 0 0 1 6-6h4a6 6 0 0 1 6 6v1' })]);
const PEye = (p) => _PI(p, [React.createElement('path', { key: 1, d: 'M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z' }), React.createElement('circle', { key: 2, cx: 12, cy: 12, r: 3 })]);
const PCheck = (p) => _PI(Object.assign({ sw: 3 }, p), React.createElement('path', { d: 'M20 6 9 17l-5-5' }));

function inic(n) { return (n || '?').split(' ').filter(Boolean).slice(0, 2).map((w) => w[0]).join('').toUpperCase(); }

// ── Tarjeta ──
function PCard({ t, children, style }) {
  return <div style={{ background: '#fff', border: `1px solid ${t.border}`, borderRadius: 16, padding: '22px 24px', ...style }}>{children}</div>;
}
function PLabel({ t, children }) {
  return <span style={{ display: 'block', fontSize: 11, color: t.sec, fontFamily: t.mono, textTransform: 'uppercase', letterSpacing: .8, fontWeight: 700, marginBottom: 6 }}>{children}</span>;
}
function PField({ t, label, value, onChange, placeholder, Icn, type, disabled }) {
  const [foc, setFoc] = React.useState(false);
  return (
    <label style={{ display: 'block' }}>
      <PLabel t={t}>{label}</PLabel>
      <div style={{ display: 'flex', alignItems: 'center', borderRadius: 10, background: disabled ? '#FAFBFC' : '#fff',
        border: `1.5px solid ${foc ? t.brand : t.border}`, boxShadow: foc ? '0 0 0 4px rgba(29,87,169,.1)' : 'none', transition: 'border-color .15s, box-shadow .15s' }}>
        {Icn && <span style={{ paddingLeft: 12, color: foc ? t.brand : t.ter, display: 'flex' }}><Icn size={17}/></span>}
        <input type={type || 'text'} value={value} onChange={(e) => onChange && onChange(e.target.value)} placeholder={placeholder} disabled={disabled}
          onFocus={() => setFoc(true)} onBlur={() => setFoc(false)}
          style={{ flex: 1, minWidth: 0, border: 'none', outline: 'none', background: 'transparent', padding: Icn ? '11px 12px' : '11px 14px',
            fontFamily: type === 'password' ? t.mono : t.font, fontSize: 14, color: disabled ? t.ter : t.text }}/>
      </div>
    </label>
  );
}
function PBtn({ t, children, onClick, kind, disabled }) {
  const primary = kind !== 'ghost';
  return (
    <button onClick={onClick} disabled={disabled} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, cursor: disabled ? 'default' : 'pointer',
      padding: '11px 18px', borderRadius: 11, border: primary ? 'none' : `1px solid ${t.border}`, background: primary ? t.brand : '#fff',
      color: primary ? '#fff' : t.text, fontFamily: t.font, fontSize: 14, fontWeight: 700, opacity: disabled ? .5 : 1,
      boxShadow: primary ? '0 10px 22px -12px rgba(29,87,169,.8)' : 'none' }}>{children}</button>
  );
}
function PToggle({ t, on, onChange }) {
  return (
    <button onClick={() => onChange(!on)} style={{ width: 46, height: 27, borderRadius: 999, border: 'none', cursor: 'pointer',
      background: on ? t.success : '#CDD3DB', position: 'relative', transition: 'background .2s', flexShrink: 0 }}>
      <span style={{ position: 'absolute', top: 3, left: on ? 22 : 3, width: 21, height: 21, borderRadius: '50%', background: '#fff', transition: 'left .2s', boxShadow: '0 1px 3px rgba(0,0,0,.3)' }}/>
    </button>
  );
}

function PerfilView() {
  const t = window.WC, I = window.WI;
  const isMobile = window.useIsMobile();
  const sess = (window.LOLA.api.user && window.LOLA.api.user()) || {};
  const [nombre, setNombre] = React.useState(sess.nombre || 'Administrador');
  const usuario = sess.usuario || '@admin';
  const [correo, setCorreo] = React.useState(sess.email || 'admin@lola.gt');
  const [tel, setTel] = React.useState('');
  const [savedPerfil, setSavedPerfil] = React.useState(false);

  const [actual, setActual] = React.useState('');
  const [nueva, setNueva] = React.useState('');
  const [conf, setConf] = React.useState('');
  const [show, setShow] = React.useState(false);
  const [pwMsg, setPwMsg] = React.useState(null);

  const [face, setFace] = React.useState(true);
  const [liveness, setLiveness] = React.useState(true);

  const [tab, setTab] = React.useState('perfil');

  const score = (p) => { let s = 0; if (p.length >= 6) s++; if (p.length >= 8) s++; if (/[A-Z]/.test(p) && /[0-9]/.test(p)) s++; if (/[^A-Za-z0-9]/.test(p)) s++; return s; };
  const sc = nueva ? score(nueva) : 0;
  const scColor = [t.danger, t.danger, t.warn, t.success, t.success][sc];
  const scLabel = ['Muy débil', 'Débil', 'Aceptable', 'Fuerte', 'Excelente'][sc];

  const [busyPerfil, setBusyPerfil] = React.useState(false);
  const [errPerfil, setErrPerfil] = React.useState('');
  const [busyPw, setBusyPw] = React.useState(false);

  const guardarPerfil = async () => {
    setBusyPerfil(true); setErrPerfil('');
    try {
      const r = await window.LOLA.api.actualizarPerfil({ nombre, telefono: tel, email: correo });
      if (window.LOLA.api.updateSessionUser) window.LOLA.api.updateSessionUser(r.usuario);
      if (window.__lolaRerender) window.__lolaRerender();
      setSavedPerfil(true); setTimeout(() => setSavedPerfil(false), 1600);
    } catch (e) {
      setErrPerfil(e.code === 'DUPLICATE' ? 'Ya existe una cuenta con ese correo.' : (e.message || 'No se pudo guardar.'));
    }
    setBusyPerfil(false);
  };
  const actualizarPw = async () => {
    if (!actual || !nueva) { setPwMsg({ err: true, txt: 'Completa la contraseña actual y la nueva.' }); return; }
    if (nueva.length < 8) { setPwMsg({ err: true, txt: 'La nueva contraseña debe tener al menos 8 caracteres.' }); return; }
    if (nueva !== conf) { setPwMsg({ err: true, txt: 'Las contraseñas no coinciden.' }); return; }
    setBusyPw(true);
    try {
      await window.LOLA.api.changePassword(correo, actual, nueva);
      setActual(''); setNueva(''); setConf(''); setPwMsg({ err: false, txt: 'Contraseña actualizada.' });
      setTimeout(() => setPwMsg(null), 2200);
    } catch (e) {
      setPwMsg({ err: true, txt: e.code === 'BAD_CREDENTIALS' ? 'La contraseña actual es incorrecta.' : (e.message || 'No se pudo actualizar la contraseña.') });
    }
    setBusyPw(false);
  };

  const roleName = (window.LOLA.map && sess.rol) ? window.LOLA.map.rol(sess.rol) : 'Administrador';

  return (
    <div style={{ maxWidth: 940 }}>
      <PerfilTabs t={t} tab={tab} setTab={setTab}/>
      {tab === 'idioma' && <IdiomaTab t={t}/>}
      {tab === 'apariencia' && <AparienciaTab t={t}/>}
      {tab === 'ayuda' && <AyudaTab t={t}/>}
      <div style={{ display: tab === 'perfil' ? 'flex' : 'none', flexDirection: 'column', gap: 18 }}>
      {/* Mi perfil */}
      <PCard t={t}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 18, flexWrap: 'wrap', paddingBottom: 20, borderBottom: `1px solid ${t.grid}`, marginBottom: 20 }}>
          <div style={{ position: 'relative', flexShrink: 0 }}>
            <div style={{ width: 74, height: 74, borderRadius: 18, background: `linear-gradient(158deg, ${t.brandHi}, ${t.brand})`, color: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontFamily: t.mono, fontSize: 24,
              boxShadow: '0 12px 28px -10px rgba(29,87,169,.7)' }}>{inic(nombre)}</div>
            <button title="Cambiar foto" style={{ position: 'absolute', right: -6, bottom: -6, width: 28, height: 28, borderRadius: 9, background: '#0C1826', border: '2px solid #fff', color: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><PCam size={14}/></button>
          </div>
          <div style={{ flex: 1, minWidth: 200 }}>
            <div style={{ fontSize: 22, fontWeight: 800, color: t.text, letterSpacing: -.4 }}>{nombre}</div>
            <div style={{ display: 'flex', gap: 8, marginTop: 8, flexWrap: 'wrap' }}>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, fontWeight: 700, color: t.brand, background: t.brand + '12', padding: '4px 11px', borderRadius: 999 }}><I.Shield size={13}/> {roleName}</span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, fontWeight: 600, color: t.sec, background: t.grid, padding: '4px 11px', borderRadius: 999, fontFamily: t.mono }}><PUser size={13}/> {usuario}</span>
            </div>
            <div style={{ fontSize: 12.5, color: t.ter, marginTop: 8 }}>El rol y los permisos los define un administrador en <span style={{ color: t.brand, fontWeight: 700 }}>Seguridad</span>.</div>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 16 }}>
          <PField t={t} label="Nombre completo" value={nombre} onChange={setNombre} Icn={PUser} placeholder="Tu nombre"/>
          <PField t={t} label="Usuario" value={usuario} Icn={PUser} disabled/>
          <PField t={t} label="Correo electrónico" value={correo} onChange={setCorreo} Icn={PMail} placeholder="tu@correo.com"/>
          <PField t={t} label="Teléfono" value={tel} onChange={setTel} Icn={PPhone} placeholder="0000 0000"/>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 18, flexWrap: 'wrap' }}>
          <PBtn t={t} onClick={guardarPerfil} disabled={busyPerfil}>{savedPerfil ? <><PCheck size={15}/> Guardado</> : busyPerfil ? 'Guardando…' : 'Guardar cambios'}</PBtn>
          {savedPerfil && <span style={{ fontSize: 13, color: t.success, fontWeight: 600 }}>Tus datos se guardaron.</span>}
          {errPerfil && <span style={{ fontSize: 13, color: t.danger, fontWeight: 600 }}>{errPerfil}</span>}
        </div>
      </PCard>

      {/* Contraseña */}
      <PCard t={t}>
        <div style={{ fontSize: 17, fontWeight: 800, color: t.text }}>Contraseña</div>
        <div style={{ fontSize: 13, color: t.ter, marginTop: 3, marginBottom: 18 }}>Cámbiala periódicamente. Política actual: <b style={{ color: t.text }}>mínimo 8 caracteres</b>.</div>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 16 }}>
          <div style={{ gridColumn: isMobile ? 'auto' : '1 / 2' }}><PField t={t} label="Contraseña actual" value={actual} onChange={setActual} Icn={PLock} type={show ? 'text' : 'password'} placeholder="••••••••"/></div>
          <div/>
          <PField t={t} label="Nueva contraseña" value={nueva} onChange={(v) => { setNueva(v); setPwMsg(null); }} Icn={PLock} type={show ? 'text' : 'password'} placeholder="Mínimo 8 caracteres"/>
          <PField t={t} label="Confirmar nueva contraseña" value={conf} onChange={(v) => { setConf(v); setPwMsg(null); }} Icn={PLock} type={show ? 'text' : 'password'} placeholder="••••••••"/>
        </div>
        {nueva && (
          <div style={{ marginTop: 12, maxWidth: isMobile ? '100%' : 'calc(50% - 8px)' }}>
            <div style={{ display: 'flex', gap: 4 }}>{[0, 1, 2, 3].map((i) => <span key={i} style={{ flex: 1, height: 4, borderRadius: 3, background: i < sc ? scColor : t.grid, transition: 'background .2s' }}/>)}</div>
            <div style={{ fontSize: 11.5, color: scColor, fontFamily: t.mono, marginTop: 6, fontWeight: 700 }}>Seguridad: {scLabel}</div>
          </div>
        )}
        <label style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 14, cursor: 'pointer', fontSize: 13, color: t.sec }}>
          <input type="checkbox" checked={show} onChange={(e) => setShow(e.target.checked)} style={{ accentColor: t.brand, width: 16, height: 16 }}/> Mostrar contraseñas
        </label>
        {pwMsg && <div style={{ marginTop: 14, fontSize: 13, padding: '10px 13px', borderRadius: 9,
          background: pwMsg.err ? '#FDF0EF' : t.success + '14', color: pwMsg.err ? t.danger : t.success, border: `1px solid ${pwMsg.err ? '#F2C4C0' : t.success + '55'}` }}>{pwMsg.txt}</div>}
        <div style={{ marginTop: 16 }}><PBtn t={t} onClick={actualizarPw} disabled={busyPw}>{busyPw ? 'Actualizando…' : 'Actualizar contraseña'}</PBtn></div>
      </PCard>

      {/* Reconocimiento facial */}
      <PCard t={t}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14, flexWrap: 'wrap' }}>
          <span style={{ width: 44, height: 44, borderRadius: 12, background: t.brand + '12', color: t.brand, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><I.Scan size={22}/></span>
          <div style={{ flex: 1, minWidth: 200 }}>
            <div style={{ fontSize: 17, fontWeight: 800, color: t.text }}>Acceso por reconocimiento facial</div>
            <div style={{ fontSize: 13, color: t.ter, marginTop: 3 }}>Entra a la consola con tu rostro, sin escribir la contraseña.</div>
          </div>
          <PToggle t={t} on={face} onChange={setFace}/>
        </div>
        {face && (
          <div style={{ marginTop: 18, borderTop: `1px solid ${t.grid}`, paddingTop: 18 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 12.5, color: t.success, fontWeight: 700, fontFamily: t.mono }}>
                <span style={{ width: 8, height: 8, borderRadius: '50%', background: t.success }}/> Rostro registrado
              </span>
              <PBtn t={t} kind="ghost" onClick={() => alert('Aquí se abriría la cámara para volver a registrar tu rostro.')}><I.Scan size={16}/> Registrar de nuevo</PBtn>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, marginTop: 16 }}>
              <div><div style={{ fontSize: 14, fontWeight: 700, color: t.text }}>Prueba de vida (liveness)</div>
                <div style={{ fontSize: 12.5, color: t.ter, marginTop: 1 }}>Exige parpadeo o giro para evitar fotos.</div></div>
              <PToggle t={t} on={liveness} onChange={setLiveness}/>
            </div>
          </div>
        )}
      </PCard>
      </div>
    </div>
  );
}

const IAppear = (p) => React.createElement('svg', { width: p.size || 18, height: p.size || 18, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1.9, strokeLinecap: 'round', strokeLinejoin: 'round' }, [React.createElement('circle', { key: 1, cx: 12, cy: 12, r: 9 }), React.createElement('path', { key: 2, d: 'M12 3a9 9 0 0 1 0 18z', fill: 'currentColor', stroke: 'none' })]);

// ── Apariencia real: persistida y aplicada a toda la consola ──
function lolaReadAppearance() { try { return JSON.parse(localStorage.getItem('lola_appearance') || '{}'); } catch (e) { return {}; } }
function lolaApplyAppearance() {
  var a = lolaReadAppearance(), root = document.documentElement;
  var dark = a.tema === 'oscuro' || (a.tema === 'auto' && window.matchMedia && matchMedia('(prefers-color-scheme: dark)').matches);
  root.setAttribute('data-lola-theme', dark ? 'dark' : 'light');
  root.setAttribute('data-lola-density', a.densidad === 'compacta' ? 'compacta' : 'comoda');
  if (window.WC) { window.WC.brand = a.acento || '#1D57A9'; window.WC.brandHi = a.acento || '#2E6EC4'; }
  if (!document.getElementById('lola-appearance-css')) {
    var s = document.createElement('style'); s.id = 'lola-appearance-css';
    s.textContent = 'html[data-lola-theme="dark"] main{filter:invert(.93) hue-rotate(180deg);background:#0e1116}html[data-lola-theme="dark"] main img{filter:invert(1) hue-rotate(180deg)}html[data-lola-density="compacta"] main{zoom:.93}';
    document.head.appendChild(s);
  }
}
window.lolaReadAppearance = lolaReadAppearance;
window.lolaApplyAppearance = lolaApplyAppearance;
lolaApplyAppearance();

function PerfilTabs({ t, tab, setTab }) {
  const I = window.WI;
  const items = [['perfil', 'Perfil', <PUser size={16}/>], ['idioma', 'Idioma', <I.Globe size={16}/>], ['apariencia', 'Apariencia', <IAppear size={16}/>], ['ayuda', 'Ayuda', <I.Book size={16}/>]];
  return (
    <div style={{ display: 'inline-flex', gap: 4, background: '#fff', border: `1px solid ${t.border}`, borderRadius: 12, padding: 5, marginBottom: 18, flexWrap: 'wrap' }}>
      {items.map(([id, l, ic]) => {
        const on = tab === id;
        return <button key={id} onClick={() => setTab(id)} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, cursor: 'pointer', padding: '9px 15px', borderRadius: 9, border: 'none', background: on ? t.brand + '12' : 'transparent', color: on ? t.brand : t.sec, fontFamily: t.font, fontSize: 13.5, fontWeight: on ? 700 : 600 }}>{ic} {l}</button>;
      })}
    </div>
  );
}

function IdiomaTab({ t }) {
  const [lang, setLang] = React.useState('es');
  const LANGS = [['es', 'Español', 'ES', 'Guatemala · es-GT'], ['en', 'English', 'EN', 'United States'], ['fr', 'Français', 'FR', 'France'], ['pt', 'Português', 'PT', 'Brasil'], ['nl', 'Nederlands', 'NL', 'Nederland']];
  return (
    <PCard t={t}>
      <div style={{ fontSize: 17, fontWeight: 800, color: t.text }}>Idioma de la plataforma</div>
      <div style={{ fontSize: 13, color: t.ter, marginTop: 3, marginBottom: 18 }}>Traduce las pantallas y mensajes del sistema. Los datos que tú creas no se traducen.</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {LANGS.map(([id, name, code, sub]) => {
          const on = lang === id;
          return (
            <button key={id} onClick={() => setLang(id)} style={{ display: 'flex', alignItems: 'center', gap: 13, cursor: 'pointer', textAlign: 'left', padding: '12px 14px', borderRadius: 12, border: `1.5px solid ${on ? t.brand : t.border}`, background: on ? '#F4F8FF' : '#fff' }}>
              <span style={{ width: 40, height: 30, borderRadius: 7, background: on ? t.brand : t.grid, color: on ? '#fff' : t.sec, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: t.mono, fontWeight: 800, fontSize: 12.5, flexShrink: 0 }}>{code}</span>
              <div style={{ flex: 1 }}><div style={{ fontSize: 14, fontWeight: 700, color: t.text }}>{name}</div><div style={{ fontSize: 12, color: t.ter }}>{sub}</div></div>
              {on && <span style={{ color: t.brand }}><PCheck size={18}/></span>}
            </button>
          );
        })}
      </div>
    </PCard>
  );
}

function AparienciaTab({ t }) {
  const init = window.lolaReadAppearance ? window.lolaReadAppearance() : {};
  const [tema, setTema] = React.useState(init.tema || 'claro');
  const [acento, setAcento] = React.useState(init.acento || '#1D57A9');
  const [densidad, setDensidad] = React.useState(init.densidad || 'comoda');
  const apply = (patch) => {
    const next = { tema, acento, densidad, ...patch };
    setTema(next.tema); setAcento(next.acento); setDensidad(next.densidad);
    try { localStorage.setItem('lola_appearance', JSON.stringify(next)); } catch (e) {}
    if (window.lolaApplyAppearance) window.lolaApplyAppearance();
    if (window.__lolaRerender) window.__lolaRerender();
  };
  const TEMAS = [['claro', 'Claro', '#fff', '#0C1826'], ['oscuro', 'Oscuro', '#0C1826', '#fff'], ['auto', 'Automático', 'linear-gradient(90deg,#fff 50%,#0C1826 50%)', t.text]];
  const ACENTOS = [['#1D57A9', 'Azul'], ['#1F8A5B', 'Verde'], ['#7A5AF8', 'Morado'], ['#0E9CA6', 'Teal'], ['#D98A0B', 'Ámbar']];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      <PCard t={t}>
        <div style={{ fontSize: 17, fontWeight: 800, color: t.text }}>Tema</div>
        <div style={{ fontSize: 13, color: t.ter, marginTop: 3, marginBottom: 16 }}>Se aplica al instante en toda la consola.</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px,1fr))', gap: 12 }}>
          {TEMAS.map(([id, l, bg, fg]) => {
            const on = tema === id;
            return (
              <button key={id} onClick={() => apply({ tema: id })} style={{ cursor: 'pointer', textAlign: 'left', padding: 4, borderRadius: 14, border: `1.5px solid ${on ? t.brand : t.border}`, background: '#fff' }}>
                <div style={{ height: 64, borderRadius: 10, background: bg, border: `1px solid ${t.grid}`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: fg, fontWeight: 800, fontFamily: t.mono, fontSize: 13 }}>Aa</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '8px 8px 4px' }}>{on ? <span style={{ color: t.brand, display: 'flex' }}><PCheck size={15}/></span> : <span style={{ width: 15 }}/>}<span style={{ fontSize: 13.5, fontWeight: 700, color: t.text }}>{l}</span></div>
              </button>
            );
          })}
        </div>
      </PCard>
      <PCard t={t}>
        <div style={{ fontSize: 17, fontWeight: 800, color: t.text }}>Color de acento</div>
        <div style={{ fontSize: 13, color: t.ter, marginTop: 3, marginBottom: 16 }}>El color de botones y elementos activos, en toda la consola.</div>
        <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
          {ACENTOS.map(([c, name]) => {
            const on = acento === c;
            return <button key={c} onClick={() => apply({ acento: c })} title={name} style={{ width: 42, height: 42, borderRadius: '50%', cursor: 'pointer', background: c, border: `3px solid ${on ? '#fff' : 'transparent'}`, boxShadow: on ? `0 0 0 2px ${c}` : `0 0 0 1px ${t.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff' }}>{on && <PCheck size={18}/>}</button>;
          })}
        </div>
      </PCard>
      <PCard t={t}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
          <div><div style={{ fontSize: 15, fontWeight: 800, color: t.text }}>Densidad</div><div style={{ fontSize: 13, color: t.ter, marginTop: 2 }}>Espaciado de listas y tablas.</div></div>
          <div style={{ display: 'inline-flex', gap: 3, background: t.grid, borderRadius: 10, padding: 3 }}>
            {[['comoda', 'Cómoda'], ['compacta', 'Compacta']].map(([id, l]) => { const on = densidad === id; return <button key={id} onClick={() => apply({ densidad: id })} style={{ cursor: 'pointer', padding: '8px 16px', borderRadius: 8, border: 'none', background: on ? '#fff' : 'transparent', color: on ? t.brand : t.sec, fontFamily: t.font, fontSize: 13, fontWeight: on ? 700 : 600, boxShadow: on ? '0 1px 3px rgba(0,0,0,.12)' : 'none' }}>{l}</button>; })}
          </div>
        </div>
      </PCard>
    </div>
  );
}

function AyudaTab({ t }) {
  const I = window.WI;
  const [q, setQ] = React.useState('');
  const [open, setOpen] = React.useState(0);
  const TOPICS = [
    { ic: 'Shield', h: 'Ingresar a la plataforma', s: 'Entra con tu usuario y la verificación en dos pasos (2FA).', body: 'La primera vez confirmas tu identidad con un código; luego puedes entrar con tu rostro.', cap: 'Acceso · verificación en dos pasos', steps: ['Escribe tu correo y contraseña.', 'Ingresa el código de 6 dígitos que llega a tu correo (solo la primera vez).', 'Si activaste el rostro, toca “Entrar con rostro”.'] },
    { ic: 'User', h: 'Mi perfil y reconocimiento facial', s: 'Tus datos, contraseña y acceso por rostro — para cualquier rol.', body: 'Desde Mi perfil administras tu cuenta y tu seguridad personal.', cap: 'Mi perfil · Perfil · Idioma · Apariencia · Ayuda', steps: ['Abre Mi perfil desde tu nombre en el menú.', 'Edita tus datos y guarda los cambios.', 'En Contraseña define una nueva.', 'Activa el acceso por rostro con prueba de vida.'] },
    { ic: 'Check', h: 'Aprobar contratos', s: 'Revisa documentos y habilita clientes y proveedores.', body: 'Cada solicitud llega con sus documentos para que decidas.', cap: 'Aprobaciones · cola de revisión', steps: ['Abre Aprobaciones.', 'Selecciona una solicitud de la cola.', 'Revisa los documentos adjuntos.', 'Aprueba o rechaza indicando un motivo.'] },
    { ic: 'Wallet', h: 'Comisiones y pagos', s: 'Tasa base, tasas por categoría y liquidaciones.', body: 'Controlas cuánto gana la plataforma y el flujo de pagos.', cap: 'Comisiones · tasa por categoría', steps: ['En Comisiones ajusta la tasa base.', 'Define tasas por categoría de carga.', 'En Pagos confirma recargas y libera fondos.', 'Aprueba los retiros de proveedores.'] },
    { ic: 'Megaphone', h: 'Publicidad y campañas', s: 'Anuncios para Facebook, Instagram, TikTok, WhatsApp y la app.', body: 'Creas campañas multicanal con vista previa por red social.', cap: 'Publicidad · nueva campaña', steps: ['Toca “Crear campaña”.', 'Elige objetivo, público y canales.', 'Sube el creativo y revisa la vista previa.', 'Publica o guarda como borrador.'] },
    { ic: 'Shield', h: 'Usuarios, roles y permisos', s: 'Acceso denegado por defecto; concede permisos por módulo.', body: 'Defines qué puede hacer cada persona, módulo por módulo.', cap: 'Seguridad · matriz de permisos', steps: ['Abre Seguridad.', 'Elige un usuario o un rol.', 'Marca las acciones por módulo (Lectura, Escritura, Actualización, Eliminación, Consulta).', 'Guarda los cambios.'] },
    { ic: 'Book', h: 'Auditoría', s: 'Registro inmutable de todo lo que ocurre.', body: 'Toda acción queda registrada con quién, qué y cuándo.', cap: 'Auditoría · registro inmutable', steps: ['Busca por usuario, fecha o tipo de acción.', 'Cambia entre vista de lista y tarjetas.', 'Exporta el resultado a CSV.'] },
  ];
  const rows = TOPICS.filter((x) => !q.trim() || (x.h + ' ' + x.s + ' ' + x.body).toLowerCase().includes(q.trim().toLowerCase()));
  return (
    <PCard t={t}>
      <div style={{ fontSize: 17, fontWeight: 800, color: t.text }}>Manual de usuario</div>
      <div style={{ fontSize: 13, color: t.ter, marginTop: 3, marginBottom: 16 }}>Guías paso a paso. Pulsa un tema para ver el detalle.</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, border: `1px solid ${t.border}`, borderRadius: 10, padding: '0 12px', height: 42, marginBottom: 14 }}>
        <span style={{ color: t.ter, display: 'flex' }}><I.Search size={17}/></span>
        <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Buscar en la ayuda (ej. permisos, 2FA, CSV)…" style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent', fontFamily: t.font, fontSize: 13.5, color: t.text }}/>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {rows.map((x, i) => {
          const Icn = I[x.ic] || I.Book; const on = open === i;
          return (
            <div key={i} style={{ border: `1px solid ${on ? t.brand : t.border}`, borderRadius: 12, overflow: 'hidden', background: on ? '#F4F8FF' : '#fff' }}>
              <button onClick={() => setOpen(on ? -1 : i)} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer', border: 'none', background: 'none', padding: '13px 15px', textAlign: 'left' }}>
                <span style={{ width: 34, height: 34, borderRadius: 9, background: t.brand + '14', color: t.brand, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icn size={17}/></span>
                <div style={{ flex: 1 }}><div style={{ fontSize: 14, fontWeight: 700, color: t.text }}>{x.h}</div><div style={{ fontSize: 12, color: t.ter }}>{x.s}</div></div>
                <span style={{ color: t.ter, transform: on ? 'rotate(180deg)' : 'none', transition: 'transform .2s', display: 'flex' }}><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M6 9l6 6 6-6"/></svg></span>
              </button>
              {on && (
                <div style={{ paddingBottom: 15 }}>
                  <div style={{ padding: '0 15px 12px 61px', fontSize: 13.5, color: t.sec, lineHeight: 1.6 }}>{x.body}</div>
                  <div style={{ margin: '0 15px 14px 61px', borderRadius: 12, overflow: 'hidden', border: `1px solid ${t.grid}` }}>
                    <div style={{ height: 150, background: 'repeating-linear-gradient(135deg, #eef2f7, #eef2f7 12px, #f7f9fc 12px, #f7f9fc 24px)', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 10 }}>
                      <span style={{ width: 46, height: 46, borderRadius: 12, background: '#fff', border: `1px solid ${t.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: t.brand }}><Icn size={22}/></span>
                      <span style={{ fontFamily: t.mono, fontSize: 11, color: t.ter, letterSpacing: .4 }}>{x.cap}</span>
                    </div>
                  </div>
                  <ol style={{ margin: '0 15px 0 61px', paddingLeft: 18, color: t.sec, fontSize: 13.5, lineHeight: 1.75 }}>
                    {x.steps.map((s, j) => <li key={j}>{s}</li>)}
                  </ol>
                </div>
              )}
            </div>
          );
        })}
      </div>
      <a href="https://wa.me/50254603160" target="_blank" rel="noreferrer" style={{ display: 'inline-flex', alignItems: 'center', gap: 8, marginTop: 16, textDecoration: 'none', color: t.brand, fontFamily: t.mono, fontSize: 12.5, fontWeight: 700 }}>¿Necesitas más ayuda? Escríbenos por WhatsApp →</a>
    </PCard>
  );
}

window.PerfilView = PerfilView;
