// Mi cuenta — todos los roles. Cliente solo edita email/username/password; otros también nombre.
function MiCuenta() {
  const meCache = DesasfAPI.getCurrentUser() || {};
  const [me,        setMe]        = React.useState(meCache);
  const [loading,   setLoading]   = React.useState(true);
  const [editing,   setEditing]   = React.useState({});
  const [saving,    setSaving]    = React.useState(false);
  const [msg,       setMsg]       = React.useState(null);
  const [err,       setErr]       = React.useState('');
  const [pwActual,  setPwActual]  = React.useState('');
  const [pwNueva,   setPwNueva]   = React.useState('');
  const [pwConfirm, setPwConfirm] = React.useState('');
  const [pwSaving,  setPwSaving]  = React.useState(false);
  const [pwMsg,     setPwMsg]     = React.useState(null);
  const [pwErr,     setPwErr]     = React.useState('');
  const [showPw,    setShowPw]    = React.useState(false);

  const isCliente = meCache.rol === 'cliente';
  const rolLabel = {
    dev: 'Desarrollador', admin: 'Administrador',
    gerente_general: 'Gerente general', gerente_comercial: 'Gerente comercial',
    vendedor: 'Asistente Técnico comercial', operador_planta: 'Operador planta', finanzas: 'Finanzas',
    conductor: 'Conductor', cliente: 'Cliente', solo_lectura: 'Solo lectura',
  };

  React.useEffect(() => {
    DesasfAPI.get('/auth/me')
      .then(u => {
        setMe(u);
        setEditing({
          apellidos: u.apellidos || '',
          nombres:   u.nombres   || '',
          email:     u.email     || '',
          username:  u.username  || '',
          telefono:  u.telefono  || '',
        });
      })
      .catch(e => setErr(e.message))
      .finally(() => setLoading(false));
  }, []);

  function flash(setter, value) {
    setter(value);
    setTimeout(() => setter(null), 3500);
  }

  async function guardarPerfil() {
    setErr(''); setMsg(null); setSaving(true);
    try {
      const payload = {
        email:    (editing.email || '').trim().toLowerCase(),
        username: (editing.username || '').trim() || null,
        telefono: (editing.telefono || '').trim() || null,
      };
      if (!isCliente) {
        payload.apellidos = (editing.apellidos || '').trim();
        payload.nombres   = (editing.nombres   || '').trim();
        if (!payload.apellidos || !payload.nombres) {
          setErr('Apellidos y nombres son requeridos.');
          setSaving(false);
          return;
        }
      }

      const r = await DesasfAPI.put('/auth/me', payload);
      const updated = r.user || r;
      setMe(updated);
      if (r.token && r.refreshToken) DesasfAPI.setTokens(r.token, r.refreshToken);
      flash(setMsg, 'Datos actualizados correctamente.');
    } catch (e) {
      setErr(e.message || 'No se pudo guardar.');
    } finally { setSaving(false); }
  }

  async function cambiarPassword() {
    setPwErr(''); setPwMsg(null);
    if (!pwActual || !pwNueva) { setPwErr('Completa la contraseña actual y la nueva.'); return; }
    if (pwNueva.length < 6)    { setPwErr('La nueva debe tener al menos 6 caracteres.'); return; }
    if (pwNueva !== pwConfirm) { setPwErr('La confirmación no coincide.'); return; }
    setPwSaving(true);
    try {
      await DesasfAPI.put('/auth/password', {
        password_actual: pwActual,
        password_nueva:  pwNueva,
      });
      setPwActual(''); setPwNueva(''); setPwConfirm('');
      flash(setPwMsg, 'Contraseña actualizada. Úsala en tu próximo inicio de sesión.');
    } catch (e) {
      setPwErr(e.message || 'No se pudo cambiar la contraseña.');
    } finally { setPwSaving(false); }
  }

  const initials = (me.nombre || 'U').trim().split(/\s+/).slice(0, 2)
    .map(w => w[0]).join('').toUpperCase();

  return (
    <div className="app">
      <AppSidebar active="mi-cuenta"/>
      <Topbar crumbs={[isCliente ? 'Mi cuenta' : 'Cuenta', 'Perfil']}/>
      <main className="main">
        <div className="page-head">
          <div>
            <h1>Mi cuenta</h1>
            <p>Actualiza tus datos de acceso y tu contraseña. {isCliente
              ? 'Para cambiar otros datos contacta a tu asistente técnico comercial.'
              : 'Tu rol y permisos se gestionan desde Configuración.'}</p>
          </div>
        </div>

        {loading ? (
          <div className="card"><div className="card__body" style={{ padding: 32, textAlign: 'center', color: 'var(--ink-5)' }}>Cargando…</div></div>
        ) : (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
            <div className="card">
              <div className="card__head"><h3>Tus datos</h3></div>
              <div className="card__body">
                <div className="row" style={{ gap: 14, marginBottom: 18 }}>
                  <div className="avatar" style={{ width: 56, height: 56, fontSize: 18 }}>{initials}</div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 600, fontSize: 15 }}>{me.nombre}</div>
                    <div className="muted" style={{ fontSize: 12 }}>{rolLabel[me.rol] || me.rol}</div>
                    {me.ultimo_login && (
                      <div className="muted" style={{ fontSize: 11, marginTop: 2 }}>
                        Último ingreso: {new Date(me.ultimo_login).toLocaleString('es-PE')}
                      </div>
                    )}
                  </div>
                </div>

                <div style={{ display: 'grid', gap: 12 }}>
                  {!isCliente ? (
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                      <div>
                        <label className="label">Apellidos</label>
                        <input className="input" value={editing.apellidos || ''}
                          onChange={e => setEditing({ ...editing, apellidos: e.target.value })}/>
                      </div>
                      <div>
                        <label className="label">Nombres</label>
                        <input className="input" value={editing.nombres || ''}
                          onChange={e => setEditing({ ...editing, nombres: e.target.value })}/>
                      </div>
                    </div>
                  ) : (
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                      <div>
                        <label className="label">Apellidos</label>
                        <input className="input" value={me.apellidos || ''} disabled
                          style={{ background: 'var(--ink-9)', color: 'var(--ink-4)' }}/>
                      </div>
                      <div>
                        <label className="label">Nombres</label>
                        <input className="input" value={me.nombres || ''} disabled
                          style={{ background: 'var(--ink-9)', color: 'var(--ink-4)' }}/>
                      </div>
                      <div className="muted" style={{ gridColumn: '1 / -1', fontSize: 11 }}>
                        Para cambiar tus apellidos o nombres contacta a tu asistente técnico comercial.
                      </div>
                    </div>
                  )}
                  <div>
                    <label className="label">Correo electrónico</label>
                    <input className="input" type="email" value={editing.email || ''}
                      onChange={e => setEditing({ ...editing, email: e.target.value })}/>
                    <div className="muted" style={{ fontSize: 11, marginTop: 4 }}>Lo usas para iniciar sesión.</div>
                  </div>
                  <div>
                    <label className="label">Usuario (opcional)</label>
                    <input className="input k" placeholder="ej: jperez"
                      value={editing.username || ''}
                      onChange={e => setEditing({ ...editing, username: e.target.value.replace(/[^a-zA-Z0-9._-]/g, '') })}/>
                    <div className="muted" style={{ fontSize: 11, marginTop: 4 }}>
                      3-30 caracteres · letras, números, punto, guion. Te permite ingresar sin escribir el correo.
                    </div>
                  </div>
                  <div>
                    <label className="label">Teléfono</label>
                    <input className="input k" placeholder="+51 999 123 456"
                      value={editing.telefono || ''}
                      onChange={e => setEditing({ ...editing, telefono: e.target.value })}/>
                  </div>
                </div>

                {err && <div style={{ marginTop: 12, padding: 10, background: 'var(--status-danger-bg, #fef0f0)', color: 'var(--status-danger)', borderRadius: 6, fontSize: 12 }}>{err}</div>}
                {msg && <div style={{ marginTop: 12, padding: 10, background: 'var(--status-ok-bg, #e8f6ee)', color: 'var(--status-ok, #137333)', borderRadius: 6, fontSize: 12 }}>{msg}</div>}

                <div className="row" style={{ justifyContent: 'flex-end', gap: 8, marginTop: 14 }}>
                  <button className="btn btn--ghost btn--sm"
                    disabled={saving}
                    onClick={() => setEditing({
                      apellidos: me.apellidos || '',
                      nombres:   me.nombres   || '',
                      email:     me.email     || '',
                      username:  me.username  || '',
                      telefono:  me.telefono  || '',
                    })}>
                    Revertir
                  </button>
                  <button className="btn btn--accent btn--sm" onClick={guardarPerfil} disabled={saving}>
                    {Icon.check}<span>{saving ? 'Guardando…' : 'Guardar cambios'}</span>
                  </button>
                </div>
              </div>
            </div>

            <div className="card" style={{ alignSelf: 'flex-start' }}>
              <div className="card__head"><h3>Cambiar contraseña</h3></div>
              <div className="card__body">
                <div style={{ display: 'grid', gap: 12 }}>
                  <div>
                    <label className="label">Contraseña actual</label>
                    <input className="input" type={showPw ? 'text' : 'password'}
                      value={pwActual} onChange={e => setPwActual(e.target.value)} autoComplete="current-password"/>
                  </div>
                  <div>
                    <label className="label">Nueva contraseña</label>
                    <input className="input" type={showPw ? 'text' : 'password'}
                      value={pwNueva} onChange={e => setPwNueva(e.target.value)} autoComplete="new-password"/>
                    <div className="muted" style={{ fontSize: 11, marginTop: 4 }}>Mínimo 6 caracteres.</div>
                  </div>
                  <div>
                    <label className="label">Confirmar nueva contraseña</label>
                    <input className="input" type={showPw ? 'text' : 'password'}
                      value={pwConfirm} onChange={e => setPwConfirm(e.target.value)} autoComplete="new-password"/>
                  </div>
                  <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, color: 'var(--ink-3)' }}>
                    <input type="checkbox" checked={showPw} onChange={e => setShowPw(e.target.checked)}/>
                    Mostrar contraseñas
                  </label>
                </div>

                {pwErr && <div style={{ marginTop: 12, padding: 10, background: 'var(--status-danger-bg, #fef0f0)', color: 'var(--status-danger)', borderRadius: 6, fontSize: 12 }}>{pwErr}</div>}
                {pwMsg && <div style={{ marginTop: 12, padding: 10, background: 'var(--status-ok-bg, #e8f6ee)', color: 'var(--status-ok, #137333)', borderRadius: 6, fontSize: 12 }}>{pwMsg}</div>}

                <div className="row" style={{ justifyContent: 'flex-end', marginTop: 14 }}>
                  <button className="btn btn--accent btn--sm" onClick={cambiarPassword} disabled={pwSaving}>
                    {Icon.check}<span>{pwSaving ? 'Cambiando…' : 'Cambiar contraseña'}</span>
                  </button>
                </div>
              </div>
            </div>
          </div>
        )}
      </main>
    </div>
  );
}

window.MiCuenta = MiCuenta;
